2012-01-05 88 views
2

我想从csv文件读取一列数据并为其创建直方图。我可以将数据读入数组,但无法制作直方图。下面是我做的:从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=1) 

它给我的错误:

TypeError: cannot perform reduce with flexible type 

任何想法是怎么回事?

+1

您可能需要将字符串转换为数字。我认为csv.reader只是创建字符串列表,并且numpy创建了一串字符串 – yosukesabai 2012-01-05 15:32:13

+1

你需要使用'csv'吗?我认为'np.loadtxt'会在这里做得更好(简单的代码,自动转换等)。 – 2012-01-05 15:57:44

+0

我尝试使用csv over loadtxt,因为它更好地处理非数字字段,例如列标签。但是如果csv只有数字,那么loadtxt是一个不错的选择。 – 2012-01-05 16:17:36

回答

1

修改第六行投串数字

z.append(float(data[7])) 

有了这个,我得到了一些情节与我取得的数据。

+0

这工作得很好。谢谢!!! – Labibah 2012-01-06 03:01:52

0

这里有两个选项,这人会工作,如果你所有的列是由数字:

array = np.loadtxt('thimar.csv', 'float', delimiter=',') 
n, bins, patches = plt.hist(array[:, 7], 50, normed=1) 

这个人是更好,如果你在你的文件的非数字列(即姓名,性别, ...):

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) 
+0

谢谢。我只是试过这个,它运作良好:) – Labibah 2012-01-06 03:02:56