如何计算numpy中一维数组的移动(或滚动,如果你愿意的话)百分位数/分位数?

Roy*_*Roy 3 numpy quantile pandas rolling-computation

在熊猫中,我们有pd.rolling_quantile(). 在 numpy 中,我们有np.percentile(),但我不确定如何进行滚动/移动版本。

解释我所说的移动/滚动百分位数/分位数是什么意思:

给定数组[1, 5, 7, 2, 4, 6, 9, 3, 8, 10]0.5窗口大小为 3的移动分位数(即移动百分位数 50%)为:

1
5 - 1 5 7 -> 0.5 quantile = 5
7 - 5 7 2 ->                5
2 - 7 2 4 ->                4
4 - 2 4 6 ->                4
6 - 4 6 9 ->                6
9 - 6 9 3 ->                6
3 - 9 3 8 ->                8
8 - 3 8 10 ->               8
10
Run Code Online (Sandbox Code Playgroud)

[5, 5, 4, 4, 6, 6, 8, 8]答案也是如此。为了使结果序列与输入的长度相同,一些实现插入NaNNone,同时pandas.rolling_quantile()允许通过较小的窗口计算前两个分位数值。

Sae*_*eed 6

series = pd.Series([1, 5, 7, 2, 4, 6, 9, 3, 8, 10])

In [194]: series.rolling(window = 3, center = True).quantile(.5)

Out[194]: 
0      nan
1   5.0000
2   5.0000
3   4.0000
4   4.0000
5   6.0000
6   6.0000
7   8.0000
8   8.0000
9      nan
dtype: float64
Run Code Online (Sandbox Code Playgroud)

False默认为中心。因此,您需要手动将其设置True为分位数计算窗口以对称地包含当前索引。