我想计算每个组和一个新列的百分比 例如: 数据=
Group Value
A 1
A 2
A 1
B 4
B 4
B 8
我想要得到:
Group Value Percentage
A 1 0.25
A 2 0.50
A 1 0.25
B 4 0.25
B 4 0.25
B 8 0.50
如何用pandas函数或SQL获取它?谢谢!
最佳答案
使用 Pandas :
df['Percentage'] = df.groupby('Group')['Value'].transform(lambda x: x / x.sum())
输出:
Group Value Percentage
0 A 1 0.25
1 A 2 0.50
2 A 1 0.25
3 B 4 0.25
4 B 4 0.25
5 B 8 0.50
关于python - Pandas/SQL-根据不同Group计算百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39904128/