Reverting from multiindex to single index dataframe in pandas

Question:

                       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?

Asked By: user308827

||

Answers:

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'])
Answered By: EdChum

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

Answered By: Shujaath Khan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.