Home > Net >  rearrange dataframe multi-level columns by inverting the levels
rearrange dataframe multi-level columns by inverting the levels

Time:04-28

Given a pandas.DataFrame with a column MultiIndex as follows

A      B     C
X Y Z  X Y Z X Y Z

how to rearrange the columns into this format?

X      Y     Z
A B C  A B C A B C

(I tried .columns.swaplevel(0,1), but that does not yet yield the desired grouping)

CodePudding user response:

df.swaplevel with axis=1 (for columns) is what you need.

>>> df.swaplevel(0,1, axis=1)
   X  Y  Z  X  Y  Z  X  Y  Z
   A  A  A  B  B  B  C  C  C
0  x  x  x  x  x  x  x  x  x

You can use sort_index to sort:

>>> df.swaplevel(0,1, axis=1).sort_index(level=0, axis=1)
   X        Y        Z      
   A  B  C  A  B  C  A  B  C
0  x  x  x  x  x  x  x  x  x
  • Related