Sum the values for a same time, day, and ids in python dataframe

Question:

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?

Asked By: Carlos Jo

||

Answers:

Try:

df.groupby(['id', 'day','time'], as_index=False).sum()
Answered By: Nuri Taş
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.