Arrays 从csv文件制作直方图
我试图从csv文件中读取一列数据,并为其创建直方图。我可以将数据读入数组,但无法生成直方图。以下是我所做的:Arrays 从csv文件制作直方图,arrays,csv,numpy,histogram,Arrays,Csv,Numpy,Histogram,我试图从csv文件中读取一列数据,并为其创建直方图。我可以将数据读入数组,但无法生成直方图。以下是我所做的: thimar=csv.reader(open('thimar.csv', 'rb')) thimar_list=[] thimar_list.extend(thimar) z=[] for data in thimar_list: z.append(data[7]) zz=np.array(z) n, bins, patches = plt.hist(zz, 50, normed
thimar=csv.reader(open('thimar.csv', 'rb'))
thimar_list=[]
thimar_list.extend(thimar)
z=[]
for data in thimar_list:
z.append(data[7])
zz=np.array(z)
n, bins, patches = plt.hist(zz, 50, normed=1)
这给了我一个错误:
TypeError: cannot perform reduce with flexible type
知道发生了什么吗?修改第六行,将字符串转换为数字
z.append(float(data[7]))
通过这一点,我得到了一些用我的合成数据绘制的图。这里有两个选项,如果您的所有列都由数字组成,则此选项将起作用:
array = np.loadtxt('thimar.csv', 'float', delimiter=',')
n, bins, patches = plt.hist(array[:, 7], 50, normed=1)
如果文件中有非数字列(例如名称、性别等),则此列更好:
您可能需要将字符串转换为数字。我认为csv.reader只是创建字符串列表,numpy生成字符串数组。您需要使用
csv
?我认为np.loadtxt
在这里会做得更好(代码更简单,自动转换等)。我尝试在loadtxt上使用csv,因为它更好地处理非数字字段,例如列标签。但是,如果csv只有数字,则loadtxt是一个不错的选择。@Bago-仅供参考,您可以指定skiprows=1
到loadtxt
,使其跳过列标题。但是,csv
模块将处理带有带引号的字符串(包含逗号等)的csv文件。loadtxt
未(故意)设置为处理非简单分隔符。
thimar = csv.reader(open('thimar.csv', 'rb'))
thimar_list = list(thimar)
zz = np.array([float(row[7]) for row in thimar_list])
n, bins, patches = plt.hist(zz, 50, normed=1)