如何从csv文件中读取python中的数字? [英] How to read numbers in python from csv file?

查看:1367
本文介绍了如何从csv文件中读取python中的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个csv文件,我必须计算某些列的均值. 我就是这样做的:

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])

所以我有一个字符串列表:n = ['','','1.58'...] 如何将它们转换为float? 我尝试过:

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!

推荐答案

只需在追加时进行投射:

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

或者您可能想尝试熊猫,尤其是 pandas. read_csv :

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())

这篇关于如何从csv文件中读取python中的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆