在Python中对CSV列求和

10

我正在尝试计算CSV文件中一列的总和。该文件如下:

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

这可能涉及几百行。我需要获得Value的总和(在此例中为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
3个回答

11

csv模块会逐行循环读取,不需要再遍历列。只需对int(row[1])求和即可:

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

你可以使用生成器表达式和内置函数 sum() 快速计算:

with open("file.csv") as fin:
    next(fin)
    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'

3

你可以使用pandas代替。

import pandas as pd
df2=pd.read_csv('file.csv')
df2['Value'].sum()

0
import csv

csv_file = 'file.csv'

with open(csv_file) as f:
    total = sum(int(r['Value']) for r in csv.DictReader(f))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接