83
                       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?

0

2 Answers 2

100

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'])
Sign up to request clarification or add additional context in comments.

4 Comments

What if it's dist_df.columns are MultiIndex, not rows?
@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
@DzmitryLazerka to flatten a multiindex (hierarchical) column / row index, you can use .to_flat_index(). See this answer for code example
Would this change the order of the array?
8

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.