I have a dataset that looks like this:
| id1 | id2 | time | |
|---|---|---|---|
| 0 | 56 | 99 | 2007-04-06 15:49:21 |
| 1 | 56 | 104 | 2007-04-06 18:26:13 |
| 2 | 56 | 104 | 2007-04-13 11:27:52 |
| 3 | 56 | 104 | 2007-04-13 11:28:41 |
| 4 | 56 | 104 | 2007-04-13 11:28:52 |
| 5 | 56 | 104 | 2007-04-13 11:33:25 |
| 6 | 56 | 104 | 2007-04-13 14:35:52 |
| 7 | 104 | 56 | 2007-04-13 11:28:23 |
| 8 | 104 | 56 | 2007-04-13 11:29:46 |
| 9 | 128 | 105 | 2007-03-27 18:39:45 |
| 10 | 217 | 256 | 2007-03-29 14:55:57 |
I would like to drop all observation where for the same pair of IDs the time value is within 5 minutes of the previous row. It also should be "rolling" meaning if there are three observation where the second is 4 minutes from the first and the third is 4 minutes from the second, I only keep the first row. Also it doesn't matter if an Id is in the id1 or Id2 column.
So the output of the dataframe above should be:
| id1 | id2 | time | |
|---|---|---|---|
| 0 | 56 | 99 | 2007-04-06 15:49:21 |
| 1 | 56 | 104 | 2007-04-06 18:26:13 |
| 2 | 56 | 104 | 2007-04-13 11:27:52 |
| 3 | 56 | 104 | 2007-04-13 14:35:52 |
| 4 | 128 | 105 | 2007-03-27 18:39:45 |
| 5 | 217 | 256 | 2007-03-29 14:55:57 |
The best I could come-up is:
for i in range(1, len(df)):
if df['time'].iloc[i] <= df['time'].iloc[i-1] + pd.Timedelta(minutes=5):
df = df.drop(i)
df = df.reset_index(drop=True)
else:
continue
but: 1. it raises an indexer is out-of-bounds error. 2. It doesn't "roll". 3. It distinguishes if an id is in the id1 or id2 column.
Thank you in advance with your help!