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

Sum columns values with common values in another column

I have this dataframe:

enter image description here

I want to sum all the distances that have been done each day, giving the next dataframe:

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

enter image description here

distances = [
    (32.2,1),
    (40.2,1),
    (22.5,2),
    (37.6,2),
    (5.6,2),
    (5.8,3),
    (9.7,3),
    (10.2,3),
    (12.3,4),
    (15.2,4),
]
             
expected_result = [
    (72.5,1),
    (65.5,2),
    (25.7,3),
    (27.5,4),
]
             
distances = pd.DataFrame(distances, columns = ['distance','day'])
expected_result = pd.DataFrame(expected_result, columns = ['distance','day'])

I’m new to pandas so I don’t know exactly how to do it.

>Solution :

You can group the data by "day" then sum it

distances = distances.groupby('day').sum()

If you want to sort the data according to distance you can use this

distances = distances.sort_values(by=['distance'], ascending=False)

enter image description here

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