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 values of a column where the column name has been duplicated?

I have a dataframe:

df = pd.DataFrame({'grps': list('aaabbcaabcccbbc'), 
                'vals': [12,345,-3,1,45,14,4,52,54,23,235,-21,57,-3,87]})

I want to find the sum of ‘vals’ of each group: a,b,c

I’ve tried using the .sum() function but I’m struggling on how to group all the values of the same letter.

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

>Solution :

You can use GroupBy.sum :

out= df.groupby("grps", as_index=False).sum()

# Output :

print(out)

  grps  vals
0    a   410
1    b   154
2    c   338
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