经过几次尝试和错误,我想出了一个办法。我不确定它是否是最佳的,但它是矢量化的。代码如下:
import pandas as pd
import numpy as np
gap = 3 # You can modify this value
# Create dataframe with True/False sequences
tmp = pd.DataFrame([True, False, True, False, False, True, False, False, False, True, False, False,
False, False, False, True], columns=['Binary'])
# Convert to zeros and ones to make computations and filtering
tmp['col_0'] = (tmp==False).astype(int)
# Count consecutive False in a vectorized way. Check Note 1 for next line
tmp['col_1'] = ((tmp['col_0'] * (tmp['col_0'].groupby((tmp['col_0'] != tmp['col_0'].shift()).cumsum()).cumcount() + 1)) > gap).astype(int)
# Create NaN in lines we are interested to remove
tmp['col_2'] = tmp['col_1'].replace(1, np.nan)
# Finish creating NaN in lines before we reached the 'gap' value. Check Note 2 for next segment
for counter in range(1, gap + 1):
tmp['col_2'] = tmp['col_2'] + tmp['col_1'].shift(-counter)
tmp['col_2'] = tmp['col_2'].replace(1, np.nan)
# The shift() function creates NaN at the end of the Dataframe. I need to verify the last lines (length of dataframe - gap) are ok. Check Note 3
tmp.iloc[np.where(tmp[len(tmp) - gap:]['col_1'] == 0)[0] + len(tmp) - gap, 2] = 0
# Drop the NaN lines
tmp.dropna(inplace=True)
注1:检查python pandas - creating a column which keeps a running count of consecutive values
注 2:我在这里问了一个向量化的问题:How to vectorize a function that uses both row and column elements of a dataframe,@andrej-kesely 非常友好地解决了这个问题。从这里我得到了使用 pd.shift() 的想法。也许这可以以更好的方式进行矢量化,但到目前为止我就是这样理解的
注3:勾选pandas dataframe fails to assign value to slice subset
如您所见,有几个步骤,但都是矢量化的。
如果这有用,我会感谢您的支持并将其标记为解决方案