Convert CSV to numpy

Question:

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)
Asked By: user3062459

||

Answers:

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

Answered By: Simon

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
Answered By: Mike Müller
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.