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 the values for a same time, day, and ids in python dataframe

I have a data frame, which has 4 columns. I want to sum up the values for a id with a same time and day. Here is a simple example: for id = 1, we have two value at time 17:00:00 at day 2013-07-10, so we sum up the value 1, 5 for that. for id = 3 we have two also, so we sum up 5+8=13 for that, and only keep one time and day for it.

import pandas as pd
df = pd.DataFrame()
df['id'] = [1, 1, 1, 2, 2,3, 3]
df['day'] = ['2013-07-10', '2013-07-10', '2013-07-10','2014-02-27','2014-02-27', '2014-02-27', '2014-02-27']
df['time'] = ['17:00:00', '17:00:00', '18:30:00','18:30:00',' 18:30:00', '06:30:00', '06:30:00' ]
df['val'] = [1, 5,9,2,5,8,5]
    id  day     time    val
    1   2013-07-10  17:00:00    1
    1   2013-07-10  17:00:00    5
    1   2013-07-10  18:30:00    9
    2   2014-02-27  18:30:00    2
    2   2014-02-27  18:30:00    5
    3   2014-02-27  06:30:00    8
    3   2014-02-27  06:30:00    5

here is the desired output:

    id       day        time    val
    1   2013-07-10  17:00:00    6
    1   2013-07-10  18:30:00    9
    2   2013-07-10  18:30:00    7
    3   2014-02-27  06:30:00    13

Could you please help me with that?

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 :

Try:

df.groupby(['id', 'day','time'], as_index=False).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