在Python中将所有值添加到CSV列中 [英] Add all values in a CSV column in Python

查看:252
本文介绍了在Python中将所有值添加到CSV列中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个像这样的CSV文件:

 日期,活动,价值
1,租金,500
7,工资付款,1000

我希望将value列中的所有数字相加。到目前为止,我的代码是这样:

  cr = csv.reader(open(file.csv,rb) )

for row in cr:
print row

#print sum(Value)

如何计算该值的总和?



谢谢。

csv 文件的第一行是'Day,Event,Value' / code>,您可以使用生成器表达式 sum()

 >>> cr = csv.reader(open(file.csv,rb))
>>> cr.next()
>>>> print sum(int(x [2])for x in cr)
1500


These seems like something very simple, but search as I might I just can't get past it.

I have a CSV file like this:

Day,Event,Value
1,"Rent",500
7,"Wage Payments",1000

I wish to add up all of the numbers in the 'value' column. So far, my code is this:

cr = csv.reader(open("file.csv","rb"))

for row in cr:    
    print row

#print sum(Value)

How could I go about summing that value?

Thank you.

解决方案

Considering the first line of csv file is 'Day,Event,Value', you can use a generator expression with sum()

>>> cr = csv.reader(open("file.csv","rb"))
>>> cr.next()
>>> print sum(int(x[2]) for x in cr)
1500

这篇关于在Python中将所有值添加到CSV列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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