Home > Software engineering >  pandas count consecutive values in a column
pandas count consecutive values in a column

Time:09-18

There is my data after comparing two dataframes:

frames = [9,12,14,15,16,17,18,22,23,24,25,30]
df1 = [75,75,75,75,75,75,75,75,75,75,75,75]
df2 = [*[0]*len(df1)]
d = {'frames':frames,'a':df1, 'b':df2}
df = pd.DataFrame(d)

I need to count consecutive frames, count starts after two consecutive values:

counter = [0,0,0,0,1,1,1,0,0,1,1,0]
df['c'] = counter
result = counter.count(1)

I can't figure it out, maybe there is a way to do it with pandas? Thanks!

CodePudding user response:

You can use diff() to check for a sequence and shift() to skip extra matches.

df['c'] = ((s := df.frames.diff().eq(1)) & s.shift(1)).astype(int)
print(df)
    frames   a  b  c
0        9  75  0  0
1       12  75  0  0
2       14  75  0  0
3       15  75  0  0
4       16  75  0  1
5       17  75  0  1
6       18  75  0  1
7       22  75  0  0
8       23  75  0  0
9       24  75  0  1
10      25  75  0  1
11      30  75  0  0
  • Related