在创建合并多列的新列时,如何在 pandas 中多次旋转我的数据框?

How do I pivot my dataframe multiple times in pandas while creating a new column merging multiple columns?

我发现这是一个相当复杂的挑战,因为我需要将数据框中的多个列合并在一起,然后多次旋转 table(我认为)。

所以提供的输入是我过滤掉的这个数据框:

                       name      X      Y
0      Mathematics House AB  0.123  0.111
2111   Physical Science Hut  0.124  0.112
9412   Primary Education LO  0.125  0.113
1234   Tertiary Universitas  0.126  0.114
12411  Principle of Physics  0.127  0.115
12373  Chemical Industry A1  0.128  0.116

输出应该是这样的:

                  label  Z      
   Mathematics House AB  X  0.123
                         Y  0.111
   Physical Science Hut  X  0.124
                         Y  0.112
   Primary Education LO  X  0.125
                         Y  0.113
   Tertiary Universitas  X  0.126
                         Y  0.114
   Principle of Physics  X  0.127
                         Y  0.115
   Chemical Industry A1  X  0.128
                         Y  0.116

其中 Z 代表尚未创建的新列。我目前正在使用一种非常 hacky 的技术,它将一些列作为 numpy 数组并尝试重建它。结果并不理想,也不符合预期。有没有办法不使用 numpy 直接操作数据框?它似乎是一个多次旋转的工具。我目前使用的方法是 df.pivot(index='name', columns='Z').T.unstack().T,我之前让 df['Z'] = '' —— 确实非常丑陋和老套,而且它没有得到我想要呈现的内容。

这是stack不是pivot

df.set_index('name').stack()
Out[186]: 
name                  
MathematicsHouseAB   X    0.123
                     Y    0.111
PhysicalScienceHut   X    0.124
                     Y    0.112
PrimaryEducationLO   X    0.125
                     Y    0.113
TertiaryUniversitas  X    0.126
                     Y    0.114
PrincipleofPhysics   X    0.127
                     Y    0.115
ChemicalIndustryA1   X    0.128
                     Y    0.116
dtype: float64

编辑:

df=df.set_index('name').stack()
df.index.names=['name', 'Z']
df
Out[263]: 
                           0
name                Z       
MathematicsHouseAB  X  0.123
                    Y  0.111
PhysicalScienceHut  X  0.124
                    Y  0.112
PrimaryEducationLO  X  0.125
                    Y  0.113
TertiaryUniversitas X  0.126
                    Y  0.114
PrincipleofPhysics  X  0.127
                    Y  0.115
ChemicalIndustryA1  X  0.128
                    Y  0.116