[英]Convert daily data in pandas dataframe to monthly data
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. 我想使用上面我的df中每个月的最后一天来计算月收益。 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.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'
TypeError:仅对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.
非常感谢您的帮助。
Your index is not a DatetimeIndex. 您的索引不是DatetimeIndex。 But you can make it a 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.