Convert dataframe index with format YYYYMM and type 'pandas.core.indexes.base.Index' to datetime index

Viewed 667

I have a dataframe df. I tried to convert it to DateTime index but didn't get an exact solution yet.

         India    China
date    
2018M06     2        1
2018M05     1        2
2018M04     3        1
   .       .        .
   .       .        .
   .       .        .

Here date in an index of dataframe type 'pandas.core.indexes.base.Index' .

1 Answers

Use pd.to_datetime on the index:

df.index = pd.to_datetime(df.index, format='%Y%m')

>>> df
            India  China
date                    
2018-06-01      2      1
2018-05-01      1      2
2018-04-01      3      1

[EDIT: for your edited input datatframe]:

df.index = pd.to_datetime(df.index, format='%YM%m')

>>> df
            India  China
date                    
2018-06-01      2      1
2018-05-01      1      2
2018-04-01      3      1
Related