在python中汇总一个csv列

时间:2012-11-22 16:50:19

标签: python csv sum

我正在尝试在csv文件中对列进行求和。该文件看起来像:

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

这可以在数百行的范围内。我需要在终端上打印出的总值(在这种情况下它将是25)。到目前为止,我有一些代码,但它导致的数字要小得多。在对其进行故障排除时,我进行了总和的打印,并意识到它不是总和12 + 10 + 3,而是实际上打破了每列中的数字并且总和为1 + 2 + 1 + 0 + 3,这显然等于很多总数较少。这是我的代码,如果有人可以提出建议会很棒!

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

1 个答案:

答案 0 :(得分:9)

csv模块逐个循环遍历您的行,然后无需在列上循环。只需加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()内置函数:

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

请注意,在Python中,字符串也是序列,因此当您执行for col in row[1]:时,您将循环遍历row[1]的各个字符;所以对于你的第一行12

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