Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pivot Pandas DataFrame into hierarchical columns/change column hierarchy

I want to pivot a dataframe like:

       dim1   Value_V     Value_y   instance
0      A_1     50.000000        0   instance200
1      A_2   6500.000000        1   instance200
2      A_3     50.000000        0   instance200
3      A_4   4305.922313        1   instance200

Into a dataframe with hierarchical columns like that:

              A_1               A_2               A_3                .....
              Value_V  Value_y  Value_V  Value_y  Value_V  Value_y
instance200   50       0        6500     1        50       0

I tried df = df.pivot(index = "instance", columns = "dim1"), but it will only give me a frame like that:

              Value_V               Value_y                              
              A_1   A_2   A_3 ....  A_1  A_2  A_3 ....
instance200   50    6500  50        0    1    0

How can i change the hierarchy of the columns?

like image 867
Pat Patterson Avatar asked Mar 17 '23 04:03

Pat Patterson


2 Answers

I figured it out by myself:

df = df.swaplevel(0,1,axis = 1).sort(axis = 1)

will do

like image 158
Pat Patterson Avatar answered Mar 30 '23 06:03

Pat Patterson


What you need is reorder_levels and then sort the columns, like this:

import pandas as pd

df = pd.read_clipboard()

df
Out[8]:
dim1    Value_V Value_y instance
0   A_1 50.000000   0   instance200
1   A_2 6500.000000 1   instance200
2   A_3 50.000000   0   instance200
3   A_4 4305.922313 1   instance200
In [9]:

df.pivot('instance', 'dim1').reorder_levels([1, 0], axis=1).sort(axis=1)
Out[9]:
dim1        A_1             A_2             A_3             A_4
            Value_V Value_y Value_V Value_y Value_V Value_y Value_V Value_y
instance                                
instance200 50      0       6500    1       50      0       4305.922313 1
like image 33
Anzel Avatar answered Mar 30 '23 07:03

Anzel