How to read numbers in python from csv file?

I have a csv file and I have to calculate the average value for some columns. Here is how I did it:

file=csv.reader(open('tab.csv','r')) n=[] for row in file: n.append(row[8]) 

So I have a list of strings: n = ['', '', '1.58' ...] How can I convert them to float? I tried:

 n_values=np.array(n) n_values[n=='']='0' values=n_values.astype(np.float) np.mean(values) 

But the average value is wrong, because I have to skip empty lines, not counting. Thanks for the help!

+5
source share
1 answer

Just add by adding:

  n.append(float(row[8])) 

If there are blank lines, catch them before adding.

 try: n.append(float(row[8])) except ValueError: continue 

Or you can try pandas, in particular pandas.read_csv :

 import pandas as pd df = pd.read_csv("in.csv") print(df["col_name"].mean()) 
+9
source

All Articles