Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when changing date format in dataframe index

Tags:

pandas

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.

like image 797
JamesHudson81 Avatar asked Jan 03 '23 16:01

JamesHudson81


1 Answers

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
like image 142
MaxU - stop WAR against UA Avatar answered Jan 11 '23 15:01

MaxU - stop WAR against UA