首页 > 解决方案 > 将 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)

但我收到与上述相同的错误消息。非常感谢您的帮助。

标签: pythonpandas

解决方案


您的索引不是 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

推荐阅读