[英]Sum the amount of boolean values (based on value groups within different column) inside a new column
I have a DataFrame with the following structure:我有一个具有以下结构的 DataFrame:
col1 col2 col3
1 True
1 True
2 False
2 True
2 False
3 False
3 False
In 'col3'
I would like to sum the amount of True
values for each group of values in 'col1'
.在
'col3'
中,我想对'col1'
中每组值的True
值的数量求和。
For the example above, it should look like this:对于上面的示例,它应该如下所示:
col1 col2 col3
1 True 2
1 True 2
2 False 1
2 True 1
2 False 1
3 False 0
3 False 0
Let us do transform
让我们进行
transform
df['col3']=df.groupby('col1').col2.transform('sum')
Try尝试
df['col3'] = df.groupby('col1', sort=False).col2.transform(sum)
Output Output
col1 col2 col3
0 1 True 2.0
1 1 True 2.0
2 2 False 1.0
3 2 True 1.0
4 2 False 1.0
5 3 False 0.0
6 3 False 0.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.