如何总计CSV列?

时间:2017-05-18 02:13:21

标签: python csv

我想使用下面的python脚本在CSV文件中总计一列。但是,我收到以下错误。

invalid literal for int() with base 10: '7.3'

我的剧本出了什么问题?

import csv

cr = csv.reader(open("companylist.csv","rb"))
cr.next() # to skip the header 

total = 0
for row in cr:  
   total += int(row[2])
   # possibly do other things with data/rows 

print total

3 个答案:

答案 0 :(得分:3)

不是创建总变量并递增它,而是可以通过Generator Expression一次性完成。

import csv

with open("book1.csv", "rb") as csv_file:
    reader = csv.DictReader(csv_file)
    total = sum(float(row["column_name_here"]) for row in reader)
print(total)

答案 1 :(得分:1)

您正在尝试使用语句

将非整数字符串值转换为int
def test(x, y):
    for row, item in x.iteritems():
        x = float(len(item))
    for row, item in y.iteritems():
        if len(item) == 0:
            return (0)
        else:
            y = float(len(item))
            return (x/y)`

使用total += int(row[2]) # possibly do other things with data/rows 代替它:

float()

答案 2 :(得分:0)

如上所述,转为float而不是int

import csv

cr = csv.reader(open("companylist.csv","rb"))
cr.next() # to skip the header 

numbers = (float(row[2]) for row in cr)
total = sum(numbers)

print total