Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating a column with sum of multiple columns grouped by name in panda

I have a dataset and I need to get the sum from two other columns and group them by name.

DF

 a       b        c
Joe      1        0
Joe      1        0
Joe      0        1
Adam     1        0
Adam     0        1
Adam     0        0

Desired Output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  a        b      c       d
 Joe       1      0       1
 Joe       1      0       2
 Joe       0      1       3
 Adam      1      0       1
 Adam      0      1       2
 Adam      0      0       2 

I have tried df['d'] = df.groupby('a')['b','c'].sum()

When I do this I get NaN as a result.

>Solution :

You need to do a cumulative sum grouped on that column.
Something like this should work

df['sum'] = df['b'] + df['c']
df['d'] = df.groupby('a')['sum'].cumsum()

which gives


a       b    c  sum d
0   Joe 1   0   1   1
1   Joe 1   0   1   2
2   Joe 0   1   1   3
3   Adam 1  0   1   1
4   Adam 0  1   1   2
5   Adam 0  0   0   2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading