收到错误“ValueError:索引必须是单调的”

问题描述

我有一些关于股票 SRE 的分钟数据,这是一个 csv 文件。我已经导入它并使用数据创建了一个数据框。然后我创建了一个滚动的 20 天移动平均线,但出现错误。 代码是:

product_images

虽然我收到错误:

import pandas as pd
ticker = 'SRE'
df = pd.read_csv('/Volumes/Seagate Portable/S&P 500 List/{}.txt'.format(ticker))
df.columns = ['Extra','Dates','Open','High','Low','Close','Volume']
df.drop(['Extra','Volume','Low'],axis=1,inplace=True)
df.Dates = pd.to_datetime(df.Dates)
df.set_index('Dates',inplace=True)
df = df.between_time('9:30','16:00')
df[f'MA {ticker}'] = df.rolling('20d').mean()

解决方法

df.sort_index(inplace = True) 就在 df.rolling('20D') 行之前应该可以解决问题。

TimeSeries 上的 .rolling() 函数要求按时间(-index)对行进行排序,即。 e. time(-index) 应该稳步增加。这样做是为了防止用户不期望的巨大计算成本。只需事先按索引排序即可满足该要求。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...