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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With