pandas create groups based on previous value

Viewed 64

I have a DataFrame which is sorted by an integer column v1:

   v1
0   1
1   5
2   6
3  12
4  15
5  23
6  24
7  25
8  33

I want to group values in v1 like this: If a value - prev_value < 5, they have the same group.
For that, I want to give an increasing number for each group.

So I want to create another column, v1_group, which will have the output:

   v1  v1_group
0   1         1 
1   5         1  
2   6         1
3  12         2  # 12 - 6 > 5, new group
4  15         2
5  23         3
6  24         3
7  25         3
8  33         4

I need to do the same task with a datetime column: group values if value - prev_value < timedelta.

I know I can solve this using a standard for loop. Is there a better pandas way?

1 Answers

IIUC,

df['v1_group'] = df.v1.diff().ge(5).cumsum() + 1

Output:

   v1  v1_group
0   1         1
1   5         1
2   6         1
3  12         2
4  15         2
5  23         3
6  24         3
7  25         3
8  33         4
Related