我有一个数据集,看起来像:
sp_data.head()
Out[21]:
Date Open High Low Close Adj Close Volume
0 1927-12-30 17.660000 17.660000 17.660000 17.660000 17.660000 0
1 1928-01-03 17.760000 17.760000 17.760000 17.760000 17.760000 0
2 1928-01-04 17.719999 17.719999 17.719999 17.719999 17.719999 0
3 1928-01-05 17.549999 17.549999 17.549999 17.549999 17.549999 0
4 1928-01-06 17.660000 17.660000 17.660000 17.660000 17.660000 0
其中包含每日数据,我希望每周、每月、每3个月、每6个月等获得回报。我尝试了以下方法:
sp_data_daily_returns = sp_data['Close'].pct_change()
sp_data_monthly_returns = sp_data['Close'].resample('M').ffill().pct_change()
但我得到了这个错误:
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'
我怎样才能解决这个问题
基本上,我们在必须检查其数据类型的日期应用任何转换。所以您得到的错误是基于数据类型错误的,您可以使用
pd.to_datetime()
来更改它你也可以看看这个:
Pandas Resampling error: Only valid with DatetimeIndex or PeriodIndex
相关问题 更多 >
编程相关推荐