linus
linus

Reputation: 457

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

Upvotes: 0

Views: 41

Answers (2)

Balaji Ambresh
Balaji Ambresh

Reputation: 5012

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

Upvotes: 1

BENY
BENY

Reputation: 323346

Let us do transform

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

Upvotes: 2

Related Questions