gpt4 book ai didi

python - 将百分比列添加到数据框

转载 作者:行者123 更新时间:2023-11-28 22:29:02 25 4
gpt4 key购买 nike

我有一个像下面这样的 pandas df:

User    Purchase_Count    Location_Count
1 2 3
2 10 5
3 5 1
4 20 4
5 2 3
6 2 3
7 10 5

我将如何添加一个列来计算坐标对 (Purchse_Count[i], Location_Count[i]) 占条目总数的百分比。所以例如我希望 df 看起来像:

User    Purchase_Count    Location_Count    %
1 2 3 42.85
2 10 5 28.57
3 5 1 14.28
4 20 4 14.28
5 2 3 42.85
6 2 3 42.85
7 10 5 28.57

最佳答案

pandas 解决方案是使用 groupby 然后使用 transform:

In [43]: df
Out[43]:
User Purchase_Count Location_Count
0 1 2 3
1 2 10 5
2 3 5 1
3 4 20 4
4 5 2 3
5 6 2 3
6 7 10 5

In [44]: total = len(df)

In [45]: df['percentage'] = df.groupby(['Purchase_Count', 'Location_Count']).transform(lambda r: r.count()/total)

In [46]: df
Out[46]:
User Purchase_Count Location_Count percentage
0 1 2 3 0.428571
1 2 10 5 0.285714
2 3 5 1 0.142857
3 4 20 4 0.142857
4 5 2 3 0.428571
5 6 2 3 0.428571
6 7 10 5 0.285714

编辑以提高可读性

In [53]: df['percentage'] = (df.groupby(['Purchase_Count', 'Location_Count'])
...: .transform(lambda r: r.count()/total))

In [54]: df
Out[54]:
User Purchase_Count Location_Count percentage
0 1 2 3 0.428571
1 2 10 5 0.285714
2 3 5 1 0.142857
3 4 20 4 0.142857
4 5 2 3 0.428571
5 6 2 3 0.428571
6 7 10 5 0.285714

编辑:

正如@piRSquared 所建议的,您可以使用:

df.groupby(['Purchase_Count', 'Location_Count']).transform('count') / total

相反,初步测试表明它明显更快。

关于python - 将百分比列添加到数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43266354/

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