暮色呼如
这有点“hacky”,但您需要创建一个单独的索引来区分您的值。例如,多个值对应于A和x1。这就是我所说的:df_new = df.set_index('Group')df_new = df_new.groupby(df_new.index, as_index=False).apply(lambda x: x.stack().reset_index())df_new.columns = ['Group', 'x', 'value']df_new = df_new.droplevel(axis=0, level=0).set_index(['Group', 'x'], append=True).unstack('Group').droplevel(axis=1, level=0)结果:Group A Ex x1 1.0 0.0x2 0.0 0.0x3 0.0 0.0x1 0.0 0.0x2 0.0 0.0x3 0.0 0.0x1 0.0 0.0x2 3.0 0.0x3 11.0 0.0x1 0.0 0.0x2 0.0 0.0x3 0.0 6.0x1 0.0 0.0x2 1.0 0.0x3 0.0 0.0