How to read numbers in python from csv file?

六眼飞鱼酱① 提交于 2020-01-11 02:26:07

问题


I have a csv file and I have to compute the mean for some of the columns. That's how I did:

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

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

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

But the mean is not correct because I should skip the empty strings not counting. Thank for your help!


回答1:


Just cast as you append:

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

If there are empty strings catch those before appending.

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

Or you might want to try pandas, in particular pandas.read_csv:

import pandas as pd

df = pd.read_csv("in.csv")
print(df["col_name"].mean())



回答2:


Just add quoting:

with open('tab.csv', newline='') as file:
    reader = csv.reader(file, quoting=csv.QUOTE_NONNUMERIC)
    n=[]
    for row in reader:
        n.append(row[8])


来源:https://stackoverflow.com/questions/31537187/how-to-read-numbers-in-python-from-csv-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!