关于python:如何查找具有大于阈值的一定数量值的窗口索引?

How to find index of the window which has certain number of values greater than threshold?

enter image description here

我刚刚开始学习python并为此代码苦苦挣扎。我有一个数据框,看起来如图所示。

我想在数据框中找到该窗口的第一次出现,该窗口的某些数量的值大于阈值。

例如:

假设数据框的维值为1000000。我想将其除以1000的滑动窗口,并需要知道至少1000个值中是否有大于某个阈值的10个值。如果第一个窗口(点0-999)的至少10个值不大于某个阈值,则窗口将滑动并考虑值1-1000。我必须找到第一次出现的窗口的索引,该窗口的至少10个值大于阈值。

同样,当我在这里处理流数据时,我需要在数据帧中出现此类窗口时停止搜索。

我尝试了此代码,但遇到关键错误,无法解决问题。

1
2
3
4
5
6
for i in np.arange(0,len(data)-999):
    for j in np.arange(0,1000):
        if data[i+j]>threshold:
            var_count=var_count+1
        if var_count>10:
            print("Anomaly has occurred")

样本数据看起来像这样,大约有180万行。

enter image description here

样本数据可能看起来像这样

1
2
3
4
5
data_sample=[1,1,0,0,0,2,1,1,1,1,1,2,1,1,1,1,1,1,2,1,2,2,1,0,0,2,2,2,2,1,1,1]            
data_sample=pd.DataFrame(data_sample)

threshold=1
window=5

因为我需要至少2个大于1的值,该值将返回索引18,因为在该索引处,长度为5的窗口具有至少2个大于1的值。


您可以通过卷积来实现:

1
2
3
4
5
6
7
8
threshold = 10
window_size = 5
count_threshold = 3

kernel = np.ones(window_size)
over_threshold = (data['relevant_column'] > threshold).values
running_count = np.convolve(kernel, over_threshold)
np.nonzero(running_count >= count_threshold)[0]

或使用熊猫滚动的类似想法:

1
np.where(((data['relevant_column'] > threshold).rolling(window_size).sum() >= count_threshold))