繁体   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