Combining Observations of dataframe hourly

Viewed 30

I have a pandas dataframe that looks similar to the following

Date                Measurement  Room
2014-02-03 12:48    0.50         23
2014-02-03 12:53    0.43         23
2014-02-03 12:59    0.21         23
2014-02-03 13:06    0.23         23
2014-02-03 13:13    0.10         23
...

I am trying to sum all of the measurements by hour. For example, in the above dataframe, we would have:

Date              Measurement
2014-02-03 12:00  1.14
2014-02-03 13:00  0.33

How could I accomplish this in Python?

2 Answers

You can use pd.Grouper with freq='H' here. Check out List of freq aliases here

# df['Date'] = pd.to_datetime(df['Date']) If `Date` is not already datetime.
df.groupby(pd.Grouper(key='Date', freq='H'))[['Measurement']].sum()

                     Measurement
Date                            
2014-02-03 12:00:00         1.14
2014-02-03 13:00:00         0.33

OR

df.groupby(pd.Grouper(key='Date', freq='H'))['Measurement'].sum().to_frame()

You can use the function resample:

df.resample('H')['Measurement'].sum()
Related