如何在使用python进行滚动平均期间拒绝包含带有异常条件的异常值的窗口?

问题描述 投票:0回答:1

我面临的问题是,当使用python熊猫计算滚动平均值时,如果一个或多个行包含一个异常值,我如何才能拒绝一个10行的窗口?我需要的帮助是基于以下提到的以下情况的条件逻辑

窗口中异常值的条件是:

  • 离群值的上限是15,下限是0

  • 如果窗口中异常值的出现频率大于10%,我们将拒绝该特定窗口并继续前进。

  • 如果一个窗口中异常值的发生频率小于10%,我们接受具有以下更改的特定窗口:1)将异常值替换为从非异常值的平均值得出的值,即9行的其余部分,然后再次平均相同的窗口,然后再移动下一个

到目前为止是以下代码:

_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()
python pandas outliers moving-average rolling-average
1个回答
0
投票

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(df.speed.rolling(10))的滚动窗口
  • 对于每个由10个数字组成的窗口,我们应用函数my_mean
  • my_mean首先通过将序列s中的元素小于最小值或大于最大值的情况相加来计算离群值。
  • 如果计数的异常值太大,我们只是说没有平均值,则返回非数字。
  • 否则,我们过滤掉异常值并计算其他数字的平均值(s[(s <= MAX) & (s >= MIN)].mean())。
© www.soinside.com 2019 - 2024. All rights reserved.