Search code examples
pythonpandasdatetimemulti-index

How to change date format of Multiindex?


I have this Multiindex,

Product  Date        col1
A        2019-10-31     5
         2019-11-30     7
B        2019-10-31     2
         2019-11-30     4
C        2019-10-31     7
         2019-11-30     3

I want to change it into this:

Product  Date            col1
A        September 2019     5
         October 2019       7
B        September 2019     2
         October 2019       4
C        September 2019     7
         October 2019       3

I tried, but it didn't work.

nested_df.index.levels[1] = pd.to_datetime(nested_df.index.levels[1]).strftime('%B')

I got this error.

TypeError: 'FrozenList' does not support mutable operations.

Solution

  • You can't change a frozen list, instead just re-set the whole index:

    df.index = df.index.set_levels([df.index.levels[0], df.index.levels[1].strftime('%B %Y')])