5

I have a dataframe that looks like this:

I'm using python 3.6.5 and a datetime.time object for the index

print(sum_by_time)

           Trips
  Time

00:00:00    10
01:00:00    10
02:00:00    10
03:00:00    10
04:00:00    20
05:00:00    20
06:00:00    20
07:00:00    20
08:00:00    30
09:00:00    30
10:00:00    30
11:00:00    30

How can I group this dataframe by time interval to get something like this:

                         Trips
       Time    

00:00:00 - 03:00:00        40
04:00:00 - 07:00:00        80
08:00:00 - 11:00:00       120
0

1 Answer 1

4

I think need convert index values to timedeltas by to_timedelta and then resample:

df.index = pd.to_timedelta(df.index.astype(str))

df = df.resample('4H').sum()
print (df)
          Trips
00:00:00     40
04:00:00     80
08:00:00    120

EDIT:

For your format need:

df['d'] = pd.to_datetime(df.index.astype(str))

df = df.groupby(pd.Grouper(freq='4H', key='d')).agg({'Trips':'sum', 'd':['first','last']})
df.columns = df.columns.map('_'.join)
df = df.set_index(df['d_first'].dt.strftime('%H:%M:%S') + ' - ' + df['d_last'].dt.strftime('%H:%M:%S'))[['Trips_sum']]
print (df)
                     Trips_sum
00:00:00 - 03:00:00         40
04:00:00 - 07:00:00         80
08:00:00 - 11:00:00        120
Sign up to request clarification or add additional context in comments.

6 Comments

You beat me to it! This is what I came up with! Just for future visitors, you can use 'H' for hour, 'T' for minute and 'M' for month time bins.
Awesome thanks! Any idea on how to make the index reflect the time intervals? i.e. instead of 00:00:00 write 00:00:00 - 03:00:00
@Jad - Added solution, please check it.
a different way to extract the information for the time spans, could be to use to_period on the index and use start_timeand end_time. Then one doesn't need to parse the time string again.
@Quickbeam2k1 - Good idea, thanks. I try implement it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.