我面临的问题是,当使用python熊猫计算滚动平均值时,如果一个或多个行包含一个异常值,我如何才能拒绝一个10行的窗口?我需要的帮助是基于以下提到的以下情况的条件逻辑
窗口中异常值的条件是:
离群值的上限是15,下限是0
如果窗口中异常值的出现频率大于10%,我们将拒绝该特定窗口并继续前进。
到目前为止是以下代码:
_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()
将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()
)。