Error when changing date format in dataframe index

拟墨画扇 提交于 2021-02-07 20:34:44

问题


I have the following df :

                  A         B
2018-01-02  100.000000  100.000000
2018-01-03  100.808036  100.325886
2018-01-04  101.616560  102.307700

I am looking forward to change the time format of the index, so I tried (using @jezrael s response in the link Format pandas dataframe index date):

df.index = rdo.index.strftime('%d-%m-%Y')

But it outputs :

AttributeError: 'Index' object has no attribute 'strftime'

My desired output would be:

                 A         B
02-01-2018  100.000000  100.000000
03-01-2018  100.808036  100.325886
04-01-2018  101.616560  102.307700

I find quite similar the question asked in the link above with my issue. I do not really understand why the attrError arises.


回答1:


Your index seems to be of a string (object) dtype, but it must be a DatetimeIndex, which can be checked by using df.info():

In [19]: df.index = pd.to_datetime(df.index).strftime('%d-%m-%Y')

In [20]: df
Out[20]:
                     A           B
02-01-2018  100.000000  100.000000
03-01-2018  100.808036  100.325886
04-01-2018  101.616560  102.307700


来源:https://stackoverflow.com/questions/49138447/error-when-changing-date-format-in-dataframe-index

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!