python - 将 pandas 数据框中的每日数据转换为每月数据
问题描述
我的数据框中包含每日库存数据:
Date AAPL NFLX INTC
0 2008-01-02 27.834286 3.764286 25.350000
1 2008-01-03 27.847143 3.724286 24.670000
2 2008-01-04 25.721428 3.515714 22.670000
3 2008-01-07 25.377142 3.554286 22.879999
4 2008-01-08 24.464285 3.328571 22.260000
我想在上面的 df 中使用每个月的最后一天计算每月回报。我猜测(在谷歌搜索后)重新采样是选择本月最后一个交易日的最佳方式。但这似乎不起作用:
df.set_index('Date')
m1= df.resample('M')
print(m1)
得到这个错误:
TypeError:仅对 DatetimeIndex、TimedeltaIndex 或 PeriodIndex 有效,但获得了“Index”实例
所以我认为这意味着 set_index 不起作用?
我也试过:
df= df.reset_index().set_index('Date')
m1= df.resample('M')
print(m1)
但我收到与上述相同的错误消息。非常感谢您的帮助。
解决方案
您的索引不是 DatetimeIndex。但您可以将其设为 DatetimeIndex:
df.set_index('Date', inplace=True)
df.index = pd.to_datetime(df.index)
df.resample('1M').mean()
# AAPL NFLX INTC
#Date
#2008-01-31 26.248857 3.577429 23.566
推荐阅读
- java - 模拟多个 jdbcTemplate.queryForObject 不起作用
- c# - C# 将 JSON 写入不带反斜杠的文件
- oracle - 如何在 oracle goldenGate 中修复 OGG-01163
- android - 动画后无法通过对讲访问视图
- wordpress - “我们无法预览您页面的这个区域,因为它在 IFRAME 中”wordpress 网站上的谷歌广告错误
- android - Firebase 测试实验室为 /jacoco.exec 抛出 FileNotFound
- javascript - 如何从 html 表单获取用户输入的数据并添加到 JSON 字符串以使用 JS/Jquery 在 POST 请求中发送
- python-3.x - 为什么我在运行代码时会出现此错误?错误=对已关闭文件的 I/O 操作
- node.js - 节点 - 错误:不支持方言 mariadb。支持的方言:mssql、mysql、postgres 和 sqlite
- file - 文件上传并保存在 Blazor 服务器端