簡體   English   中英

如何找到具有大於閾值的一定數量值的窗口索引?

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

在此處輸入圖片說明

我剛剛開始學習python並為此代碼苦苦掙扎。 我有一個看起來像圖中所示的數據框。

我想在數據框中找到該窗口的第一次出現,該窗口的某些數量的值大於閾值。

例如:

假設數據框的維數為1000000。 我想將其除以1000的滑動窗口,並且需要知道該1000個值是否至少有10個大於某個閾值的值。 如果第一個窗口(點0-999)的至少10個值不大於某個閾值,則窗口將滑動並考慮值1-1000。 我必須找到第一次出現的窗口的索引,該窗口的至少10個值大於閾值。

同樣在處理流數據時,當數據框中出現此類窗口時,我需要停止搜索。

我嘗試了此代碼,但遇到關鍵錯誤,無法解決問題。

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萬行。

在此處輸入圖片說明

樣本數據可能看起來像這樣

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的值。

您可以通過卷積來實現:

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]

或使用熊貓滾動的類似想法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM