简体   繁体   中英

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:

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' .

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

df['col3']=df.groupby('col1').col2.transform('sum')

Try

df['col3'] = df.groupby('col1', sort=False).col2.transform(sum)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM