Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change column level in df.pivot()

I'd like that the column introduced as argument in df.pivot() act as outter level, not inner.

This is how my dataframe looks like:

import pandas as pd

d1 = {'Zone':'Zone 00', 'Area':1,'A':2, 'B':51,'C':5,'D':1}
d2 = {'Zone':'Zone 00', 'Area':2,'A':6, 'B':5,'C':36,'D':2}
d3 = {'Zone':'Zone 01', 'Area':1,'A':2, 'B':8,'C':9,'D':22}
d4 = {'Zone':'Zone 01', 'Area':2,'A':8, 'B':55,'C':19,'D':42}
d5 = {'Zone':'Zone 02', 'Area':1,'A':14, 'B':42,'C':8,'D':23}
d6 = {'Zone':'Zone 02', 'Area':2,'A':23, 'B':96,'C':75,'D':12}

dics = (d1, d2, d3, d4, d5, d6)
df = pd.DataFrame([i for i in dics])

enter image description here

I pivot the dataframe to display the params (A, B, C, D) by zone's areas and not by the own params.

df.pivot(columns='Area', index='Zone',values=['A','B','C','D'])

But I obtain the column's level ordered in the inverse way:

enter image description here

This is what I'd like to obtain: enter image description here

I have tried df.swaplevel(axis=1) method, but no inverse grouper is set. It only changes level order.

Does anybody knows how to do it? Thanks in advance.

like image 712
Miguel Gonzalez Avatar asked Mar 16 '26 21:03

Miguel Gonzalez


1 Answers

Try swaplevel:

(df.pivot(columns='Area', index='Zone',values=['A','B','C','D'])
   .swaplevel(0,1, axis=1)
   .sort_index(axis=1)
)

Output:

Area      1              2            
          A   B  C   D   A   B   C   D
Zone                                  
Zone 00   2  51  5   1   6   5  36   2
Zone 01   2   8  9  22   8  55  19  42
Zone 02  14  42  8  23  23  96  75  12
like image 136
Quang Hoang Avatar answered Mar 18 '26 09:03

Quang Hoang