Search code examples
pythonpandasmulti-index

How to flat multiindex?


I have a dataframe with MultiIndex and level=[0,1] does not seem to work.

MultiIndex([('Datetime',    ''),
            (   'Value', 'A'),
            (   'Value', 'B')],
           names=[None, 'Col1'])



        Datetime               Value
Col1                           A          B
0       2017-10-14 00:00:00   -0.540774   0.870280
1       2017-10-14 01:00:00   -0.426617   0.720261
2       2017-10-14 02:00:00   -0.053588   0.746738
3       2017-10-14 03:00:00   0.318062    0.871044
4       2017-10-14 04:00:00   0.478168    1.060897

I tried to use .reset_index(level = [0,1]) as suggested in many similar questions, but it does not work.


Solution

  • df.columns = [col[1] if col[0] == '' else col[0] for col in df.columns]