我正在尝试按月分组日期列表,例如第1天到第31天是1月,依此类推。这是一些输入数据:
Day 1: -109.743833
Day 2: -59.743030
Day 3: -149.539798
Day 4: -134.004097
Day 5: -101.911757
Day 6: -64.655886
Day 7: 38.683420
Day 8: 14.493554
Day 9: -52.823889
Day 10: -16.754896
Day 11: 27.648000
Day 12: -8.978296
Day 13: 3.077756
Day 14: 8.925626
Day 15: -13.099969
Day 16: 36.508620
Day 17: -20.888302
Day 18: 2.014708
Day 19: 52.070549
Day 20: 14.389047
Day 21: 46.281278
Day 22: 6.589799
Day 23: 14.849905
Day 24: 21.924614
Day 25: -19.006338
Day 26: -16.249006
Day 27: 41.147836
Day 28: 25.397426
Day 29: 45.358489
Day 30: 129.366465
Day 31: 129.377892
Day 32: -16.628081
Day 33: 56.484472
Day 34: 73.509385
Day 35: 119.484387
Day 36: -21.506795
Day 37: -16.499800
Day 38: -17.491308
Day 39: 140.532548
Day 40: -8.470736
Day 41: 203.523499
我想总结按月分组的总数。这是我打印出上面的代码:
print('Day %d: %f' % (day, inverted))
我正在考虑手动做一个if else语句来总结它们,但我认为这不是一个好主意。有没有更好的方法呢?
谢谢!
修改
dataset = list()
for yhat in forecast
print('Day %d: %f' % (day, inverted))
temp = str(day) + ':' + str(inverted)
dataset.append(temp)
答案 0 :(得分:1)
假设您的输入位于字典中,整数天为键。
{1: -109.743833, 2: -59.743030, ...}
我们可以使用这些键来构建日期字符串,然后使用datetime.strptime
方法来解释它们。然后我们可以从datetime
对象
from collections import defaultdict
from datetime import datetime
month_groups = defaultdict(list)
year = 2018
for day, value in day_dict.items():
month = datetime.strptime('{:0>3}-{}'.format(day, year), '%j-%Y').month
month_groups[month].append(value)
如果有更好的方法,我不会感到惊讶,因此您可能需要仔细检查datetime
和calendar
模块,看看是否能找到我错过的东西
答案 1 :(得分:1)
根据给定年份将每天转换为月份,然后使用字典逐月转换:
from datetime import datetime
from datetime import timedelta
from collections import defaultdict
year = 2018
data = [
(32, -16.628081),
(33, 56.484472),
...
]
base = datetime(year, 1, 1)
res = defaultdict(float)
for month, val in (((base + timedelta(day - 1)).month, inverted) for day, inverted in data):
res[month] += val
print(res)