honza_p
honza_p

Reputation: 2093

How to change 2nd level index into 2nd level column in pandas DataFrame?

Say I have the following pandas DataFrame:

                          variable1     variable2
 proton_energy quantile                           
 5             0.16      36653.98080   82638.76640
               0.50      42634.57000   91758.91000
               0.84      50304.00280  102421.34800
 10            0.16      18617.96840   40715.77400
               0.50      22894.68500   48133.44500
               0.84      30622.25280   59162.39640
 ...

Maybe I am missing something really trivial, but I could not come up with an easy way how to end with this schema (values omitted):

                                    variable1              variable2
  proton_energy     quantile   0.16   0.50   0.84    0.16     0.50   0.84
  5                 .............................  ......................
  10                .............................  ......................
  ...

In other words, I want to change the 2nd-level index into 2nd-level column. Any ideas but for a set of for loops and manually constructing a new DataFrame?

Thank you

Upvotes: 3

Views: 108

Answers (1)

honza_p
honza_p

Reputation: 2093

Ok, I figured it out:

df.unstack(level=-1)

does exactly the job.

Upvotes: 1

Related Questions