Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas column multiindex into row multiindex

I have a pandas dataframe

df = pd.DataFrame([[i+10*j for i in range(6)] for j in range(5)], index=[f"item{i}" for i in range(5)])
df.columns = pd.MultiIndex.from_product((["abc", "xyz"], ["one", "two", "three"]))
      abc           xyz          
      one two three one two three
item0   0   1     2   3   4     5
item1  10  11    12  13  14    15
item2  20  21    22  23  24    25
item3  30  31    32  33  34    35
item4  40  41    42  43  44    45

I cannot figure out how to turn first level of column multiindex into row multiindex to get something like following

            one two three
item0 abc     0   1     2
      xyz     3   4     5
item1 abc    10  11    12
      xyz    13  14    15
item2 abc    20  21    22
      xyz    23  24    25
item3 abc    30  31    32
      xyz    33  34    35
item4 abc    40  41    42
      xyz    43  44    45

any hint appreciated. Thank you

like image 670
Honza S. Avatar asked Oct 24 '25 04:10

Honza S.


2 Answers

Here you go:

df.stack(level=0)
like image 71
Saravanan Natarajan Avatar answered Oct 26 '25 19:10

Saravanan Natarajan


As Quang Hoang suggested, I would check out pandas.DataFrame.stack. The solution should be:

df.stack(level=0)
like image 22
Eternal E'lir Avatar answered Oct 26 '25 18:10

Eternal E'lir