'rearrange dataframe multi-level columns by inverting the levels
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)
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
