2

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)
Elazar
  • 20,415
  • 4
  • 46
  • 67
user3062459
  • 1,587
  • 7
  • 27
  • 39

2 Answers2

2

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

Simon
  • 9,762
  • 15
  • 62
  • 119
2

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
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
  • Did you use the example file from your question or a different csv file? – Mike Müller Jan 21 '16 at 21:33
  • I needed to include the delimiter............. `data = np.genfromtxt('/Users/darchcruise/Desktop/untitled.csv', skip_header=True, delimiter=',') print(data) median_col1 = np.median(data[:,0]) print(median_col1)` – user3062459 Jan 22 '16 at 14:20