我的数据框中有每日股票数据:
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
Run Code Online (Sandbox Code Playgroud)
我想在上面的 df 中使用每个月的最后一天计算每月回报。我猜(在谷歌搜索之后)重新采样是选择当月最后一个交易日的最佳方式。但这似乎不起作用:
df.set_index('Date')
m1= df.resample('M')
print(m1)
Run Code Online (Sandbox Code Playgroud)
得到这个错误:
类型错误:仅对 DatetimeIndex、TimedeltaIndex 或 PeriodIndex 有效,但得到了“Index”的实例
所以我认为这意味着 set_index 不起作用?
我也试过:
df= df.reset_index().set_index('Date')
m1= df.resample('M')
print(m1)
Run Code Online (Sandbox Code Playgroud)
但我收到与上述相同的错误消息。非常感谢您的帮助。