63
                       NI
YEAR MONTH datetime        
2000 1     2000-01-01   NaN
           2000-01-02   NaN
           2000-01-03   NaN
           2000-01-04   NaN
           2000-01-05   NaN

In the dataframe above, I have a multilevel index consisting of the columns:

names=[u'YEAR', u'MONTH', u'datetime']

How do I revert to a dataframe with 'datetime' as index and 'YEAR' and 'MONTH' as normal columns?

user308827
  • 21,018
  • 70
  • 229
  • 377

2 Answers2

80

pass level=[0,1] to just reset those levels:

dist_df = dist_df.reset_index(level=[0,1])

In [28]:
df.reset_index(level=[0,1])

Out[28]:
            YEAR  MONTH  NI
datetime                     
2000-01-01  2000      1   NaN
2000-01-02  2000      1   NaN
2000-01-03  2000      1   NaN
2000-01-04  2000      1   NaN
2000-01-05  2000      1   NaN

you can pass the label names alternatively:

df.reset_index(level=['YEAR','MONTH'])
user308827
  • 21,018
  • 70
  • 229
  • 377
EdChum
  • 339,461
  • 188
  • 752
  • 538
  • 22
    What if it's `dist_df.columns` are MultiIndex, not rows? – Dzmitry Lazerka Feb 07 '18 at 06:12
  • @DzmitryLazerka sorry I don't understand your comment, if you have a question please post a new question, answering questions in comments is not good form on SO – EdChum Feb 07 '18 at 11:48
  • 9
    @DzmitryLazerka to flatten a multiindex (hierarchical) column / row index, you can use `.to_flat_index()`. See [this answer for code example](https://stackoverflow.com/a/55757002/7515530) – onlyphantom Apr 19 '19 at 05:49
  • Would this change the order of the array? – meesinlid Aug 23 '19 at 21:51
2

Another simple way would be to set columns for dataframe

consolidated_data.columns=country_master

ref: https://riptutorial.com/pandas/example/18695/how-to-change-multiindex-columns-to-standard-columns

Shujaath Khan
  • 1,182
  • 14
  • 22