在连续行不为零的列中查找实例?

时间:2019-01-29 16:06:22

标签: python pandas

我有一个pandas df列,其中包含1和0。有没有一种方法可以找到在列中1连续出现n次的所有实例?

例如,如果n = 4,那么我将返回1至4行和15至19行,如果为5行,我将仅获得15至19行。

Simple example

谢谢!


数据输入

l=[0,1,1,1,1,0,0,0,0,0,1,1,1,0,0,1,1,1,1,1,0,0,0]
s=pd.Series(l)

1 个答案:

答案 0 :(得分:1)

IIUC使用cumsum创建groupby密钥

s1=s[s==0].groupby(s.ne(0).cumsum()).transform('size')
n=5

s[(s==0)&(s1==n)]
Out[753]: 
5    0
6    0
7    0
8    0
9    0
dtype: int64

Dput

l=[0,1,1,1,1,0,0,0,0,0,1,1,1,0,0,1,1,1,1,1,0,0,0]
s=pd.Series(l)
相关问题