Reputation: 1631
I have following data in my CSV:
column 1 column 2
5 17
9 16
4 13
10 15
2 10
1 18
2 14
1 19
I am trying to go from CSV to dict (this part is already done correctly) and then from dict to to numpy to get the median price. However, I am getting the following error:
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
How can this code be written to work properly?
import csv
import numpy as np
storedata = []
f = open('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)
Upvotes: 2
Views: 11592
Reputation: 85482
Your header is a bit difficult to parse because you have spaces as delimiter and spaces in the header names. The easiest would be to skip the header:
>>> data = np.genfromtxt('mydata.csv', skip_header=True)
>>> median_col1 = np.median(data[:,0])
>>> median_col1
3.0
Upvotes: 2
Reputation: 10150
You can just use numpy to read the txt file directly into an array:
import numpy as np
csv = np.genfromtxt('file.csv')
From there you can proceed to get the median, or do whatever you want with the array
See this for reference: http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.genfromtxt.html
Upvotes: 2