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

How to sum up individual columns if they have the same value in a different column?

I have the following data frame:

            Names      Counts  Year
0           Jordan        1043  2000
1            Steve         204  2000
2            Brock           3  2000
3            Steve          33  2000
4             Mike          88  2000
...           ...         ...   ...
20001        Bryce           2  2015
20002        Steve          11  2015
20003        Penny          24  2015
20004        Steve          15  2015
20005        Penny           5  2015

I want to add up all the counts for each name if they appear multiple times in a year.
An example of the output might look like:

            Names      Counts  Year
0           Jordan        1043  2000
1            Steve         237  2000
2            Brock           3  2000
3             Mike          88  2000
...           ...         ...   ...
20001        Bryce           2  2015
20002        Steve          26  2015
20003        Penny          29  2015

I’ve tried the following:

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

(df[df['Names'].eq('Steve')].groupby('Year').agg({'Names': 'first', 'Counts': sum}).reset_index())

Which returns the following for individual names, but it’s not what I’m looking for.

   Year  Names  Counts
0  2000  Steve     237
1  2015  Steve      26

>Solution :

Try

df['Counts'] = df.groupby(['Names','Year'])['Counts'].transform('sum')
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