TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of ‘Ran

在使用Python处理股票时间序列数据时遇到了TypeError,问题在于数据索引不是DatetimeIndex。尽管尝试将'Date'列转换为datetime类型,但问题仍然存在。解决方案是将'Date'列设置为DataFrame的索引,这使得数据以日期为时间序列排列,从而解决了问题。
摘要由CSDN通过智能技术生成

在python中对股票进行时间序列的重分类时遇到报错

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

但是如果用yahoo的pandas股票获取函数获得的DataFrame不会出现这种报错。

网上许多人用这种方法就能解决,但是我解决不了,无论用什么方法把Date列转换时间序列都不能解决。

stock_df['Date']=pd.to_datetime(stock_df['Date'])

通过查看Excel读取和雅虎获取的两个结果,发现雅虎网上获取的以时间为序列。

[5 rows x 12 columns]
Backend TkAgg is interactive backend. Turning interactive mode on.
[*********************100%***********************]  1 of 1 downloaded
            Open  High   Low  Close  Adj Close    Volume
Date                                                    
2021-05-06  9.12  9.20  8.90   9.08       9.08  40262415
2021-05-07  9.22  9.24  8.78   8.90       8.90  58947590
2021-05-10  8.94  9.14  8.88   9.04       9.04  43689496
2021-05-11  9.04  9.14  8.66   9.07       9.07  53424412
2021-05-12  9.00  9.43  8.97   9.16       9.16  43475280

加上代码把Date设为索引后,Bug顺利解决。

stock_df = pd.DataFrame(stock_df).set_index('Date')

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冬_冬_

若觉得文章对您有用,请随意打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值