gpt4 book ai didi

python - 使用条件 groupby 计算分类列的百分比并在 Python 中计数

转载 作者:行者123 更新时间:2023-12-01 21:23:46 26 4
gpt4 key购买 nike

我想计算每个 ID 的所有行中真值的百分比。

这是我的数据示例:

id     col1    
1 True
1 True
1 False
1 True
2 False
2 False

新列应如下所示:

id     col1    num_true
1 True 0.75
1 True 0.75
1 False 0.75
1 True 0.75
2 False 0
2 False 0

这是我尝试做的:

df['num_true']= df[df['col1'] == 'True'].groupby('id')['col1'].count()
df['num_col1_id']= df.groupby('id')['col1'].transform('count')

df['perc_true']= df.num_true/df.num_col1_id

最佳答案

groupby 并应用transform 得到mean

df['num_true']=df.groupby('id').col1.transform('mean')



id col1 num_true
0 1 True 0.75
1 1 True 0.75
2 1 False 0.75
3 1 True 0.75
4 2 False 0.00
5 2 False 0.00

关于python - 使用条件 groupby 计算分类列的百分比并在 Python 中计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63394796/

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