使用滚动计算百分位数 window pandas

calculate percentile using rolling window pandas

我创建了一个 pandas 数据框作为

df = pd.DataFrame(data=[[1],[2],[3],[1],[2],[3],[1],[2],[3]])
df
Out[19]: 
   0
0  1
1  2
2  3
3  1
4  2
5  3
6  1
7  2
8  3

我计算长度 =3

的 windows 的 75% 百分位数
df.rolling(window=3,center=False).quantile(0.75)
Out[20]: 
     0
0  NaN
1  NaN
2  2.0
3  2.0
4  2.0
5  2.0
6  2.0
7  2.0
8  2.0

然后为了检查,我分别计算了第一个 window 的 75%

df.iloc[0:3].quantile(0.75)
Out[22]: 
0    2.5
Name: 0.75, dtype: float64

为什么我得到不同的值?

这是一个错误,已在 GH9413 and GH16211 中引用。

开发者给出的原因 -

It looks like the difference here is that quantile and percentile take the weighted average of the nearest points, whereas rolling_quantile simply uses one the nearest point (no averaging).

Rolling.quantile计算分位数时没有插值。

该错误已从 0.21 开始修复。


对于旧版本,修复是使用 rolling_apply

df.rolling(window=3, center=False).apply(lambda x: pd.Series(x).quantile(0.75))

     0
0  NaN
1  NaN
2  2.5
3  2.5
4  2.5
5  2.5
6  2.5
7  2.5
8  2.5