Pandas列多级索引转为行多级索引

4
我有一个pandas数据帧。
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

我无法弄清如何将列多级索引的第一级转换为行多级索引,以获得以下结果:
            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

任何提示都会受到赞赏。谢谢。


4
df.stack(level=0) - Quang Hoang
2个回答

4

Here you go:

df.stack(level=0)

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接