将CSV转换为numpy

时间:2016-01-21 19:03:38

标签: python csv python-3.x numpy

我的CSV中有以下数据:

column 1    column 2
    5         17
    9         16
    4         13
   10         15
    2         10
    1         18
    2         14
    1         19

我试图从CSV到dict(这部分已经正确完成)然后从dict到numpy以获得中位数价格。但是,我收到以下错误:

Traceback (most recent call last):File "untitled.py", line 10, in <module>
avg = np.median(row['column 1']). 

TypeError: cannot perform reduce with flexible type

如何编写此代码才能正常工作?

import csv
import numpy as np

storedata = []

f = open('/Users/darchcruise/Desktop/untitled.csv', 'r')
reader = csv.DictReader(f)
for row in reader:
    col_1 = int(row['column 1'])
    avg = np.median(row['column 1'])

print(avg)

2 个答案:

答案 0 :(得分:2)

您的标题有点难以解析,因为标题名称中有空格作为分隔符和空格。最简单的方法是跳过标题:

>>> data = np.genfromtxt('mydata.csv', skip_header=True)
>>> median_col1 = np.median(data[:,0])
>>> median_col1
3.0

答案 1 :(得分:1)

你可以使用numpy将txt文件直接读入数组:

import numpy as np
csv = np.genfromtxt('file.csv')

从那里你可以继续获得中位数,或者用数组做任何你想做的事情

请参阅此参考:http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.genfromtxt.html