normanius
normanius

Reputation: 9762

Pandas: pivot a level of a multi-header column into the row index

Let's be given a table with a multi-level header:

cols = pd.MultiIndex.from_arrays([['a','a', 'b','b'], [0,1,0,1]], 
                                 names=('I','II'))
df = pd.DataFrame(np.random.rand(3,4),columns=cols)
df.index.name = 'idx' 

I          a                   b
II         0         1         0         1
idx
0    0.851031  0.294414  0.503343  0.081551
1    0.333798  0.965863  0.206981  0.898823
2    0.520647  0.868081  0.571291  0.275164

How can I "pivot" the first column index I into the row index? To continue my example, I would like to achieve the following:

    II          0         1 
I   idx
a   0    0.851031  0.294414  
    1    0.333798  0.965863  
    2    0.520647  0.868081  
b   0    0.503343  0.081551  
    1    0.206981  0.898823  
    2    0.571291  0.275164  

It is assured that the columns have the proper shape for such an operation.

Upvotes: 2

Views: 1551

Answers (1)

sacuL
sacuL

Reputation: 51345

You can chain 2 calls to unstack:

df.unstack('idx').unstack('II')

II            0         1
I idx                    
a 0    0.406855  0.666815
  1    0.930418  0.204731
  2    0.715580  0.432077
b 0    0.879814  0.278757
  1    0.294891  0.001818
  2    0.453212  0.452945

Upvotes: 5

Related Questions