对于一个项目,我有一个csv文件,其中包含此类信息的年份,状态和许多火灾。我需要一个问题来汇总多年来发生的每起火灾,以找出哪一个是最多的。我用该代码解决了这个问题:

year,"state","month","number","date"
1998,"Acre","Janeiro",234,1998-01-01
1998,"Acre","Janeiro",7,1999-01-01
2000,"Acre","Janeiro",55,2000-01-01
2001,"Tocantins","Janeiro",45,2001-01-01


import csv

file_amazon = open('amazon.txt', 'w')

with open('data.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    years = set()
    liste_addition = []
    maxi = 0
    worst_year = 0
    for row in reader:
        years.add(row['year'])
    for y in years:
        year_to_test = y
        if row['year'] == year_to_test:
          liste_addition = liste_addition.append(int(row['number'].replace('.', '')))
          is_it = sum(liste_addition)
    if is_it > maxi:
      worst_year = sum(liste_addition)

print (worst_year)


TypeError: NoneType object is not iterable (line 17)无效

最佳答案

您可以使用collections.Counter如下所示:

import csv
from collections import Counter

with open('data.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    fires_per_year = Counter()
    for row in reader:
        fires_per_year[int(row['year'])] += int(row['number'])

print (fires_per_year.most_common(1))

关于python - 如何通过加法查找csv文件的最大值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58868094/

10-12 23:31