【发布时间】:2019-01-15 17:24:58
【问题描述】:
我正在尝试使用 to_datetime() 方法将 Pandas 数据帧的索引转换为日期时间,但出现异常。
对于一个玩具可重现的例子:
我的数据:
json格式:
'{"0":{"Id":1,"Name":"Lewis Alexander","Organization":"Nomura Securities International","Dec 2018":3.25,"June 2019":3.25,"Dec 2019":3.0,"June 2020":3.0,"Dec 2020":2.88},"1":{"Id":2,"Name":"Scott Anderson","Organization":"Bank of the West","Dec 2018":3.19,"June 2019":3.5,"Dec 2019":3.47,"June 2020":3.1,"Dec 2020":2.6},"2":{"Id":3,"Name":"Paul Ashworth","Organization":"Capital Economics","Dec 2018":3.25,"June 2019":3.0,"Dec 2019":2.5,"June 2020":2.25,"Dec 2020":2.25},"3":{"Id":4,"Name":"Daniel Bachman","Organization":"Deloitte LP","Dec 2018":3.2,"June 2019":3.4,"Dec 2019":3.5,"June 2020":3.6,"Dec 2020":3.7},"4":{"Id":5,"Name":"Bernard Baumohl","Organization":"Economic Outlook Group","Dec 2018":3.1,"June 2019":3.35,"Dec 2019":3.6,"June 2020":3.9,"Dec 2020":4.2}}'
当我尝试时:
df3.index.to_datetime()
我收到以下错误消息:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-53-5ff789e24651> in <module>()
----> 1 df3.index.to_datetime()
AttributeError: 'Index' object has no attribute 'to_datetime'
【问题讨论】:
-
to_datetime是一个顶级函数,它不是 Index 对象的方法,所以它应该是df3.index = pd.to_datetime(df3.index) -
OP 有两个故障点。 @EdChum 确定了一个。另一个是当前索引不适合成为
DatetimeIndex,这也需要解决。
标签: python pandas datetime indexing