Reverting from multiindex to single index dataframe in pandas

PythonPandas

Python Problem Overview


                       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?

Python Solutions


Solution 1 - Python

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'])

Solution 2 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser308827View Question on Stackoverflow
Solution 1 - PythonEdChumView Answer on Stackoverflow
Solution 2 - PythonShujaath KhanView Answer on Stackoverflow