0

I try get mean from csv line. I get data from csv in string list, further i convert it to array with numpy. Its work perfect when i try plot some graphics. But when i calculate mean i get some errors with my data.

If i use NumPy i get:

TypeError: cannot perform reduce with flexible type

If i use statistics library i get:

TypeError: can't convert type 'string' to numerator/denominator

If i check my array with comand 'type' on iPython i see that it numpy.ndarray type.

Whats wrong with my array? Can you explain, why convert numpy.asarray for matplotlib work perfect, but get wrong type for different operation.

import csv
import numpy as np
import statistics as stat
life_exp=[]
with open('country.csv') as csvfile:
   datareader = csv.reader(csvfile)
   for row in datareader:
    if datareader.line_num!=1:
        life_exp.append(row[1])
array_life_exp = np.asarray(life_exp) 
print(stat.mean(array_life_exp))
print(np.mean(array_life_exp))
2
  • Can you provide some lines from your csv? Commented Jun 18, 2015 at 8:38
  • @VladMironov Its simple example from OpenIntro Statistics book. Afghanistan,49.72,121.63,4 Albania,77.59,14.12,45. I take a second number of each row. (49.72 from first line, and 77.59 from second etc.) Commented Jun 18, 2015 at 8:42

1 Answer 1

1

Try this:

from pandas import read_csv

data = read_csv('country.csv')
print(data.iloc[:,1].mean())

This code will convert your csv to pandas dataframe with automatic type conversion and print mean of the second column.

Sign up to request clarification or add additional context in comments.

7 Comments

It work for me like magic. But whats wrong with NumPy? It needs me for plotting charts. Do you not, why don't work .asarray converting for me?
data.iloc[:,1] is np.array :)
Because numpy convert all your elements to str: In [144]: np.asarray(['1',23,'4.']) Out[144]: array(['1', '23', '4.'], dtype='<U2')
Thank you.I promise to read the documentation on this method:)
You're welcome! Check dtype value in np.asarray
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.