[英]How can we reject a window containing an outlier during rolling average using python?
[英]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 并继续下一步。
到目前为止,这是以下代码:
_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
...
这里发生的情况如下:
df.speed.rolling(10)
)my_mean
。my_mean
首先计算异常值的数量,方法是将系列s
中的元素小于最小值或大于最大值的情况的数量相加。s[(s <= MAX) & (s >= MIN)].mean()
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.