python - 用python重新采样字典中的时间序列数据
问题描述
我将每日价格历史数据以下列格式存储在字典中:
test =
{
datetime(2020, 1, 15): 15.99,
datetime(2020, 1, 16): 18.99,
datetime(2020, 1, 17): 20.99,
datetime(2020, 1, 18): 14.99
.......
}
我可以用以下方法绘制这些数据:
x = list(test.keys())
y = list(test.values())
plt.plot(x,y)
但我想将我的数据重新采样为每月一次。我怎样才能做到这一点?
解决方案
这就是你所追求的吗?您可以将您的 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')
推荐阅读
- google-cloud-platform - (gcloud.compute.images.create)无法获取资源:字段“resource.rawDisk.source”的值无效
- mongodb - MongoDB 无法解析查询(2dsphere):Java API
- reactjs - 反应:页面重新加载后本地存储 getItem() 不起作用
- spring - 我不知道如何使用es7.12。许多功能不再可用
- r - 图例 ggplot 使用 geom_vline
- amazon-web-services - 如何在 AWS 中添加 SQLite 数据库?
- android - 从 android 设备获取 CPU 温度
- gradle - 是否可以将特定的测试类绑定到测试运行器分支?
- rest - ColdFusion Rest 网络服务停止工作
- python - 如何在 PySpark 中进行会话过滤?