2 回答
TA贡献1824条经验 获得超8个赞
如果想要聚合值,例如按sum组:
df1 = df.groupby('Group').sum().T.rename_axis(None, axis=1).rename_axis('Group').reset_index()
print (df1)
Group A E
0 x1 0.0 0.0
1 x2 0.0 0.0
2 x3 0.0 0.0
3 x4 0.0 0.0
4 x5 0.0 0.0
5 x6 0.0 0.0
6 x7 0.0 0.0
7 x8 0.0 0.0
编辑:
df2 = df.set_index('Group').T.rename_axis(None, axis=1).rename_axis('Group').reset_index()
print (df2)
Group A A E E A
0 x1 0.0 0.0 0.0 0.0 0.0
1 x2 0.0 0.0 0.0 0.0 0.0
2 x3 0.0 0.0 0.0 0.0 0.0
3 x4 0.0 0.0 0.0 0.0 0.0
4 x5 0.0 0.0 0.0 0.0 0.0
5 x6 0.0 0.0 0.0 0.0 0.0
6 x7 0.0 0.0 0.0 0.0 0.0
7 x8 0.0 0.0 0.0 0.0 0.0
编辑1:
df = (df.set_index('Group')
.groupby(level=0)
.apply(lambda x: x.stack().reset_index(level=0, drop=True))
.rename_axis(None)
.rename_axis('Group', axis=1)
.T
.reset_index())
print (df)
Group A E
0 x1 1.0 0.0
1 x2 0.0 0.0
2 x3 0.0 0.0
3 x1 0.0 0.0
4 x2 0.0 0.0
5 x3 0.0 0.0
6 x1 0.0 0.0
7 x2 3.0 0.0
8 x3 11.0 0.0
9 x1 0.0 0.0
10 x2 0.0 0.0
11 x3 0.0 6.0
12 x1 0.0 0.0
13 x2 1.0 0.0
14 x3 0.0 0.0
TA贡献1853条经验 获得超9个赞
这有点“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 E
x
x1 1.0 0.0
x2 0.0 0.0
x3 0.0 0.0
x1 0.0 0.0
x2 0.0 0.0
x3 0.0 0.0
x1 0.0 0.0
x2 3.0 0.0
x3 11.0 0.0
x1 0.0 0.0
x2 0.0 0.0
x3 0.0 6.0
x1 0.0 0.0
x2 1.0 0.0
x3 0.0 0.0
添加回答
举报