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

Combine rows where variables are the same using python pandas

I have a pandas dataframe that has rows like this

   Same1  Same2  Diff3  Encoded1  Encoded2  Encoded3
0     33     22    150         0         0         0
1     33     22    300         1         0         1

What I want to achieve is to combine all rows where the ‘Same1’ and ‘Same2’ variables are the same, by adding up the other variables.

   Same1  Same2  Diff3  Encoded1  Encoded2  Encoded3
0     33     22    450         1         0         1

What would be the cleanest way to achieve this using pandas?

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

Executable python code:
https://trinket.io/python3/1da371fd04

>Solution :

You can try

out = df.groupby(['Same1', 'Same2']).agg(sum).reset_index()
print(out)

   Same1  Same2  Diff3  Encoded1  Encoded2  Encoded3
0     33     22    450         1         0         1
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