在python中总计一个csv列 [英] Sum a csv column in python

查看:207
本文介绍了在python中总计一个csv列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图对csv文件中的列求和。该文件如下所示:

I'm trying to make a sum of a column in a csv file. The file looks like:

Date  Value
2012-11-20  12
2012-11-21  10
2012-11-22  3

这可以在数百行。我需要得到的总价值(在这种情况下,将是25)印在终端上。我到目前为止有一些代码,但它导致一个比它应该总和更小的数字。当排除故障时,我做了和的打印,意识到,而不是总和12 + 10 + 3,它实际上打破了每一列中的数字,总和为1 + 2 + 1 + 0 + 3,这显然等于一个小总数。

This can be in the range of hundreds of rows. I need to get the total of Value (in this case it would be 25) printed on to a terminal. I so far have some code but it's resulting in a much smaller figure than it should sum. When troubleshooting it, I did a print of the sum and realized that instead of summing 12 + 10 + 3, it actually breaks the numbers in each column and sums as 1 + 2 + 1 + 0 + 3, which obviously equals to a much smaller total. Here's my code, if someone could make a recommendation would be great!

with open("file.csv")) as fin:
  headerline = fin.next()
  total = 0
  for row in csv.reader(fin):
    print col # for troubleshooting
    for col in row[1]:
      total += int(col)
  print total


推荐答案

csv 模块循环遍历您的行,没有必要然后遍历列。只需要 int(row [1])

The csv module loops over your rows one by one, there is no need to then loop over the column. Just sum int(row[1]):

with open("file.csv") as fin:
    headerline = fin.next()
    total = 0
    for row in csv.reader(fin):
        total += int(row[1])
    print total

您可以使用生成器表达式的快捷方式, sum()内置函数:

You can use a shortcut with a generator expression and the sum() built-in function:

with open("file.csv") as fin:
    fin.next()
    total = sum(int(r[1]) for r in csv.reader(fin))

请注意,在Python中,字符串也是序列,所以当在行[1] / code>你正在循环 row [1] 的个别字符;所以对于您的第一行, 1 2

Note that in Python, strings are sequences too, so when you do for col in row[1]: you are looping over the individual characters of row[1]; so for your first row that'd be 1 and 2:

>>> for c in '123':
...     print repr(c)
...
'1'
'2'
'3'

这篇关于在python中总计一个csv列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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