HHH
HHH

Reputation: 6475

How to add a new column based on an aggregate function in pandas

I have a pandas dataframe as follows

A, B
----
a, 2
a, 5
a, 6
b, 1
b, 2

I'd like to groupby column A and sum up the values in column B and append it as another column and create the following dataframe

A, B, SUM
--------
a, 2, 13
a, 5, 13
a, 6, 13
b, 1, 3
b, 2, 3

How can I do that in pandas?

Upvotes: 3

Views: 2865

Answers (1)

BENY
BENY

Reputation: 323316

Using transform

df.assign(SUM=df.groupby('A').B.transform('sum'))
Out[15]: 
   A  B  SUM
0  a  2   13
1  a  5   13
2  a  6   13
3  b  1    3
4  b  2    3

Upvotes: 4

Related Questions