如何从csv文件中读取python中的数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31537187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read numbers in python from csv file?
提问by Alice
I have a csv file and I have to compute the mean for some of the columns. That's how I did:
我有一个 csv 文件,我必须计算某些列的平均值。我就是这样做的:
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=['','','1.58'...] 如何将这些转换为浮点数?我试过:
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!
但平均值不正确,因为我应该跳过不计算的空字符串。感谢您的帮助!
采纳答案by Padraic Cunningham
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:
或者你可能想尝试熊猫,特别是pandas.read_csv:
import pandas as pd
df = pd.read_csv("in.csv")
print(df["col_name"].mean())
回答by syviad
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])