Reputation: 316
My data frame has 3 columns [C1-C3]
C1 C2 C3
a h 1
b i 0
c j 0
d k 1
e l 1
f m 1
g n 0
I am interested in filtering its rows based on criteria regarding the previous and next values Specifically, I would like to keep all rows, where the C3 has the pattern 0-1-1 (previous_value = 0 and next_value = 1). Thus, in the example that is used above, the data frame should be transformed into:
C1 C2 C3
d k 1
Upvotes: 2
Views: 70
Reputation: 146
With .shift()
method, you can shift index by desired number of periods.
df[(df.C3.shift(1)==0) & (df.C3==1) & (df.C3.shift(-1)==1)]
C1 C2 C3
3 d k 1
Upvotes: 0
Reputation: 323226
Using shift
m = df.C3.shift(1).eq(1) & df.C3.eq(1) & df.C3.shift(-1).eq(1)
0 False
1 False
2 False
3 False
4 True
5 False
6 False
Name: C3, dtype: bool
df = df[m]
Upvotes: 2