Rotate Pandas Multi-Index to Column

I have a framework with two index levels:

value Trial measurement 1 0 13 1 3 2 4 2 0 NaN 1 12 3 0 34 

What I want to do for this:

 Trial measurement value 1 0 13 1 1 3 1 2 4 2 0 NaN 2 1 12 3 0 34 

How can i do this?

I need this because I want to aggregate the data according to the instructions here , but I cannot select such columns if they are used as indexes.

+108
python pandas flatten dataframe multi-index
Nov 21 '13 at 0:37
source share
3 answers

The reset_index () function is the pandas DataFrame method, which will pass the index values ​​to the DataFrame as columns. The default parameter for the parameter is drop = False (which will store the index values ​​in columns).

All you have to do is add .reset_index(inplace=True) after the DataFrame name:

 df.reset_index(inplace=True) 
+137
Sep 08
source share

This does not really apply to your case, but it may be useful to know to others (such as me 5 minutes ago). If one multi-index has the same names as this:

  value Trial Trial 1 0 13 1 3 2 4 2 0 NaN 1 12 3 0 34 

df.reset_index(inplace=True) will cause the created columns to not have common names.

Then you need to rename the multi-index with df.index = df.index.set_names(['Trial', 'measurement']) to get:

  value Trial measurement 1 0 13 1 1 3 1 2 4 2 0 NaN 2 1 12 3 0 34 

And then df.reset_index(inplace=True) will work like a charm.

I ran into this problem after grouping by year and month by datetime column (not by index) with the name live_date , which meant that both year and month were called live_date .

+14
Nov 17 '17 at 17:46 on
source share

As mentioned in the @ cs95 comment, to skip only one level, use:

df.reset_index(level=[...])

This avoids overriding the desired index after the reset.

0
May 20 '19 at
source share



All Articles