我有以下数据框:
test=pd.DataFrame({'MKV':[50,1000,80,20],
'Rating':['A','Z','A','A'],
'Sec':['I','I','I','F']})
test.groupby(['Rating','Sec'])['MKV'].apply(lambda x: x/x.sum())
gives results:
0 0.38
1 1.00
2 0.62
3 1.00
最佳答案
我认为您不需要进行groupby
。您可以使用 set_index
进行旋转和 unstack
,然后标准化列:
# Perform the pivot.
test = test.set_index(['Rating','Sec'], append=True).unstack(['Rating','Sec'])
# Normalize the columns.
test = test/test.sum()
# Rename columns as appropriate.
test.columns = [','.join(c[1:]) for c in test.columns]
结果输出:
A,I Z,I A,F
0 0.384615 NaN NaN
1 NaN 1.0 NaN
2 0.615385 NaN NaN
3 NaN NaN 1.0
关于python - 如何旋转数据框分组结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38983427/