这就是你所追求的吗?您可以将您的 dict 转换为具有日期时间索引的 df,然后以这种方式重新采样,按总和进行聚合。必须使用 datetime.datetime() 而不是您示例中的 datetime()。
test = {
datetime.datetime(2020, 1, 15): 15.99,
datetime.datetime(2020, 1, 16): 18.99,
datetime.datetime(2020, 1, 17): 20.99,
datetime.datetime(2020, 1, 18): 14.99,
datetime.datetime(2020, 2, 18): 17.99,
datetime.datetime(2020, 2, 19): 21.99
}
# make a df and transpose it with .T
df = pd.DataFrame(test, index=[0]).T
# rename column 0 so it's more descriptive
df.columns = ['monthly_price_sum']
# resample and choose to aggregate values by sum, but could use max, min, mean, etc.
df = df.resample('M').sum()
print(df)
monthly_price_sum
2020-01-31 70.96
2020-02-29 39.98
如果你想回到一个字典,你可以这样做。 Zip 很好地避免了在 new_dict 中的多余嵌套。
new_dict = dict(zip(df.index, df['monthly_price_sum]))
print(new_dict)
{Timestamp('2020-01-31 00:00:00', freq='M'): 70.96, Timestamp('2020-02-29 00:00:00', freq='M'): 39.98}
您可以像这样绘制输出。
df.plot(xlabel='month', ylabel='monthly price sum')