gpt4 book ai didi

python - 如何通过加法找到csv文件的最大值

转载 作者:行者123 更新时间:2023-12-01 00:22:23 25 4
gpt4 key购买 nike

对于一个项目,我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com