简体   繁体   English

在Python 3.6.2中计算csv文件的总和

[英]calculating sum of csv file in Python 3.6.2

I am using Python 3.6.2 and have a csv file that looks like this: 我正在使用Python 3.6.2,并且具有如下所示的csv文件:

STATE,RATE,DEATHS
IA,4.2,166
NH,4.2,52
MA,4.3,309
CA,4.4,"2,169"
CO,4.6,309
ID,4.6,106
NY,4.6,"1,087"
VT,4.6,27
NJ,4.7,487
WA,4.9,432

I am trying to calculate the sum of the "RATE" column. 我正在尝试计算“比率”列的总和。 However, with my current code below I keep getting the error: "TypeError: 'float' object is not iterable". 但是,在下面的当前代码中,我不断收到错误消息:“ TypeError:'float'对象不可迭代”。 I am fairly new to Python and am not sure what I'm doing wrong. 我对Python相当陌生,不确定我在做什么错。

import csv
with open('infant_mortality.csv', 'r') as f:
  next(f) #skips the first row
  for row in csv.reader(f):
    total = sum(float(row[1]))
  print('The total is {}'.format(total))

Thanks for the help! 谢谢您的帮助!

How about: 怎么样:

import pandas as pd

df = pd.read_csv('infant_mortality.csv')

print('The total is {}'.format(df['RATE'].sum()))

You're usin sum() which requires an iterable like a list, simply add a starting value to total and then sum all values to total with total += value 您使用的是sum() ,它需要像列表那样的可迭代对象,只需将起始值添加到合计中,然后将所有值合计成具有total += value

import csv
with open('infant_mortality.csv', 'r') as f:
  next(f) #skips the first row
  total = 0
  for row in csv.reader(f):
    total += float(row[1])
  print('The total is {}'.format(total))

sum() expect a iterable object, but when you write sum(float(row[1])) , row[1] is a single value, not iterable like a list (the 'row' list in your case) sum()期望有一个可迭代的对象,但是当您编写sum(float(row [1]))时 ,row [1]是单个值,不可像列表一样进行迭代(在您的情况下为“ row”列表)

From python docs 来自python文档

sum(iterable[, start]) sum(iterable [,开始])

Sums start and the items of an iterable from left to right and returns the total. 求和从左到右开始,迭代的项返回总数。 start defaults to 0. The iterable's items are normally numbers, and the start value is not allowed to be a string. start默认为0。iterable的项目通常是数字,并且起始值不允许为字符串。

Example of use sum() 使用示例sum()

list_number = [2,3,5]
print sum(list_number)
10

Maybe the code bellow can help you. 也许下面的代码可以为您提供帮助。

import csv
total = 0
with open('infant_mortality.csv', 'r') as f:
  next(f) #skips the first row
  for row in csv.reader(f):
    total += float(row[1])
  print('The total is {}'.format(total))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM