簡體   English   中英

如何使用 python 在滾動平均期間拒絕包含異常值的 window?

[英]How to reject a window containing an outlier with a condition during rolling average using python?

我面臨的問題是,在使用 python pandas 計算滾動平均值時,如果一行或多行包含異常值,我如何拒絕 10 行的 window? 我需要的幫助是基於下面提到的以下場景的條件邏輯

window 中異常值的條件是:

  • 異常值的上限為 15,下限為 0

  • 如果 window 中異常值的出現頻率大於 10%,我們拒絕該特定 window 並繼續下一步。

  • 如果 window 中異常值的出現頻率小於 10%,我們接受特定的 window 並進行以下更改: 1) 將異常值替換為從非異常值的平均值得出的值,即 Z652AFCZ9888B2006 9 行,然后在移動下一個之前再次平均相同的 window

到目前為止,這是以下代碼:

_filter = lambda x: float("inf") if x > 15 or x < 0 else x

#Apply the mean over window with inf to result those values in  
result = df_list["speed"].apply(_filter).rolling(10).mean().dropna()

#Print Max rolling average
print("The max rolling average is:")

result.max()

通過自定義聚合 function 使用rolling

df = pd.DataFrame({"a": range(100), "speed": np.random.randint(0, 17, 100)})

MAX = 15
MIN = 0
def my_mean(s):
    outlier_count = ((s<MIN) | (s > MAX)).sum()
    if outlier_count > 2: # defined 2 as the threshold - can put any other number here
        return np.NaN
    res =  s[(s <= MAX) & (s >= MIN)].mean()
    return res

df["roll"] = df.speed.rolling(10).apply(my_mean)

在一個示例中,這會導致:

    ...
    35  35  8   9.444444
    36  36  14  9.666667
    37  37  11  9.888889
    38  38  16  10.250000
    39  39  16  NaN
    40  40  15  NaN
    41  41  6   NaN
    42  42  9   11.375000
    43  43  2   10.000000
    44  44  8   9.125000
    ...

這里發生的情況如下:

  • 我們創建一個大小為 10 的滾動 window ( df.speed.rolling(10) )
  • 對於每個由 10 個數字組成的 window,我們應用 function my_mean
  • my_mean首先計算異常值的數量,方法是將系列s中的元素小於最小值或大於最大值的情況的數量相加。
  • 如果計數異常值太大,我們只是說沒有均值並返回非數字。
  • 否則,我們過濾異常值並計算其他數字的平均值( s[(s <= MAX) & (s >= MIN)].mean() )。

暫無
暫無

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

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