I've read through a lot of answers on how to aggregate rows in a pandas dataframe but I've had a hard time figuring out how to apply it to my case. I have a dataframe containing trips data for vehicles. So each vehicle within a given day can do several trips. Here's an example below:
| vehicleID | start pos time | end pos time | duration (seconds) | meters travelled |
|---|---|---|---|---|
| XXXXX | 2021-10-26 06:01:12+00:00 | 2021-10-26 06:25:06+00:00 | 1434 | 2000 |
| XXXXX | 2021-10-19 13:49:09+00:00 | 2021-10-19 13:59:29+00:00 | 620 | 5000 |
| XXXXX | 2021-10-19 13:20:36+00:00 | 2021-10-19 13:26:40+00:00 | 364 | 70000 |
| YYYYY | 2022-09-10 15:14:07+00:00 | 2022-09-10 15:29:39+00:00 | 932 | 8000 |
| YYYYY | 2022-08-28 15:16:35+00:00 | 2022-08-28 15:28:43+00:00 | 728 | 90000 |
It often happens that the start time of a trip, on a given day, is only a few minutes after the end time of the previous trip, which means that these can be chained into a single trip.
I would like to aggregate the rows so that if the new start pos time overlaps with the previous pos time, or a gap of less than 30 minutes happens between the two, these become a single row, summing the duration of the trip in seconds and meters travelled, obviously by vehicleID. The new df should also contain those trips that didn't require the aggregation (edited for clarity). So this is the output I'm trying to get:
| vehicleID | start pos time | end pos time | duration (seconds) | meters travelled |
|---|---|---|---|---|
| XXXXX | 2021-10-26 06:01:12+00:00 | 2021-10-26 06:25:06+00:00 | 1434 | 2000 |
| XXXXX | 2021-10-19 13:20:36+00:00 | 2021-10-19 13:59:29+00:00 | 984 | 75000 |
| YYYYY | 2022-09-10 15:14:07+00:00 | 2022-09-10 15:29:39+00:00 | 932 | 8000 |
| YYYYY | 2022-08-28 15:16:35+00:00 | 2022-08-28 15:28:43+00:00 | 728 | 90000 |
I feel like a groupby and an agg would be involved by I have no clue how to go about this. Any help would be appreciated! Thanks!