【发布时间】:2021-05-22 15:56:26
【问题描述】:
我的 csv 数据看起来像这样:
ID, DATE, mm
251691,01/01/2016,16.6
251691,02/01/2016,4.4
251691,08/01/2016,3.7
120530,07/01/2019,55.5
120530,22/04/2019,1.8
我想把每年所有的“mm”和 ID 相加
我想要得到的结果是这样的:
('251691', '2016') : (sum_of_mm_for_each_station_in_that_year, number_of_total_rain_days)
那个:
('251691', '2016') : (24.7, 3)
这是我的代码:
answer = {}
with open(filename) as f:
header = line_to_list(f.readline())
if header[0] != 'ID':
raise Exception("Bad")
for line in f.readlines():
row = line_to_list(line)
date = row[1]
mm = row[2]
year = date [-4:]
answer[row[0],year] = (mm, date)
函数 line_to_list:
def line_to_list(line):
''' converts a csv line (string) to a list of items '''
line = line.rstrip('\n')
return [s for s in line.split(',')]
我无法对元素求和。 我想每年按 ID 分组并对元素求和,但我不能使用 pandas 等任何模块。
有人可以帮我吗? 谢谢!
【问题讨论】:
-
line_to_list函数的作用是什么?如果那是自定义函数,最好也添加该函数。 -
嘿,我添加了这个功能。谢谢