pandas 将熊猫数据框中的每日数据转换为每月数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50997339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:43:32  来源:igfitidea点击:

Convert daily data in pandas dataframe to monthly data

pythonpandas

提问by Eksana Stasis

My dataframe has daily stock data in it:

我的数据框中有每日股票数据:

       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  

I'd like to calculate monthly returns using the last day of each month in my df above. I'm guessing (after googling) that resample is the best way to select the last trading day of the month. But this doesn't seem to work:

我想在上面的 df 中使用每个月的最后一天计算每月回报。我猜(在谷歌搜索之后)重新采样是选择当月最后一个交易日的最佳方式。但这似乎不起作用:

df.set_index('Date')  
m1= df.resample('M')
print(m1)

get this error:

得到这个错误:

TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'

类型错误:仅对 DatetimeIndex、TimedeltaIndex 或 PeriodIndex 有效,但得到了“Index”的实例

So I think that means the set_index isn't working?

所以我认为这意味着 set_index 不起作用?

I've also tried:

我也试过:

df= df.reset_index().set_index('Date')  
m1= df.resample('M')
print(m1)

But I get the same error message as above. Thanks much for your help.

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

回答by DYZ

Your index is not a DatetimeIndex. But you can make it a DatetimeIndex:

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