Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas MultiIndex change order of one level ONLY

I have a dataframe with multiindex columns:

 |A    |B
 |1 |2 |1 |2
0|a  b  c  d

I would like to swap level one to get:

 |A    |B
 |2 |1 |2 |1
0|b |a |d |c

But with

df.sort_index(axis=1, level=1)

I get:

 |A|B|A|B
 |1|1|2|2
0|a|c|b|d

Please help

Many thanks

like image 623
Tomasz Avatar asked Jan 27 '23 16:01

Tomasz


1 Answers

Assuming they have the same label, you can use reindex with level=1:

df

   A     B   
   1  2  1  2
0  a  b  c  d

df.reindex([2, 1], level=1, axis=1)

   A     B   
   2  1  2  1
0  b  a  d  c

To generalise, you can access MultiIndex.levels:

df.reindex(df.columns.levels[1][::-1], level=1, axis=1)

   A     B   
   2  1  2  1
0  b  a  d  c

If the second level values are not the same for all first level labels, use

df.loc[:, ::-1].reindex(df.columns.levels[0], level=0, axis=1)

   A     B   
   2  1  2  1
0  b  a  d  c
like image 200
cs95 Avatar answered Feb 11 '23 07:02

cs95