根据上一个和下一个值过滤熊猫数据框

时间:2020-01-30 16:33:01

标签: python python-3.x pandas

我的数据框有3列[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

我有兴趣根据有关上一个和下一个值的条件过滤其行。具体来说,我想保留所有行,其中C3的格式为 0-1-1 (previous_value = 0,next_value = 1)。因此,在上面使用的示例中,数据帧应转换为:

C1  C2  C3
d   k   1

2 个答案:

答案 0 :(得分:2)

使用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]

答案 1 :(得分:0)

使用.shift()方法,可以按所需的周期数移动索引。

df[(df.C3.shift(1)==0) & (df.C3==1) & (df.C3.shift(-1)==1)]

    C1  C2  C3
3   d   k   1