Skip to content
Advertisement

Grouping all the rows with close timestamps in pandas dataframe

I have a df that looks like this, it contains frequencies recorded at some specific time and place.

JavaScript

I want to group all the rows which are just 2 seconds apart (like there are 3 rows index 5-7 which have a time difference of just 2 seconds). Similarly, index 8-10 also have the same difference and I want to place them in a separate group and keep only these unique groups.

so far I have tried this,

JavaScript

It helps a little as I have to manually insert a time duration in which I am looking for close timestamps records. Still, in my case, I don’t have specific time intervals as there can be 50 or more consecutive rows with a gap of 2 seconds in-between for the next two minutes. I just want to keep all these rows in a unique group.

Advertisement

Answer

My solution is to greate a column Group which groups the rows for which the difference is small.

First sort the column Time (if necessary): df = df.sort_values('Time').

Now create the groups:

JavaScript

Now you can do

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement