gpt4 book ai didi

python - 如何按分组总和划分 Pandas 列中的元素

转载 作者:行者123 更新时间:2023-12-04 07:32:22 26 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





pandas divide row value by aggregated sum with a condition set by other cell

(1 个回答)



Pandas DataFrame divide single column by the sum of the column groups

(1 个回答)


3个月前关闭。




我有一个看起来像这样的数据框,df1:

col1   col2
A 2
A 3
A 4
B 4
B 8
现在,我想计算 col2 中值的百分比 col1 中的每个独特项目.因此我希望结果是:
col1   col2
A 0.22
A 0.33
A 0.33
B 0.33
B 0.67
因此, col2 的总和对于 col1 中的唯一元素必须为 1 .有谁知道如何在不使用 for 循环的情况下做到这一点?

最佳答案

使用 GroupBy.transform sum s 到系列并除以原始列 col2 :

df['col2'] /= df.groupby('col1')['col2'].transform('sum')
#working like
#df['col2'] = df['col2'] / df.groupby('col1')['col2'].transform('sum')
print (df)
col1 col2
0 A 0.222222
1 A 0.333333
2 A 0.444444
3 B 0.333333
4 B 0.666667

关于python - 如何按分组总和划分 Pandas 列中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67883309/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com