3

在熊猫中,我们有pd.rolling_quantile(). 在 numpy 中,我们有np.percentile(),但我不知道如何做它的滚动/移动版本。

为了解释我所说的移动/滚动百分位数/分位数的含义:

给定数组[1, 5, 7, 2, 4, 6, 9, 3, 8, 10],窗口大小为 3 的移动分位数0.5(即移动百分位数 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

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

4

2 回答 2

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

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

于 2018-02-16T20:41:01.330 回答
3

我们可以用 来创建滑动窗口np.lib.stride_tricks.as_strided,作为一个函数实现strided_app-

In [14]: a = np.array([1, 5, 7, 2, 4, 6, 9, 3, 8, 10]) # input array

In [15]: W = 3 # window length

In [16]: np.percentile(strided_app(a, W,1), 50, axis=-1)
Out[16]: array([ 5.,  5.,  4.,  4.,  6.,  6.,  8.,  8.])

为了使其与输入具有相同的长度,我们可以使用 填充NaNsnp.concatenate更容易使用np.pad。因此,对于W=3,它将是 -

In [39]: np.pad(_, 1, 'constant', constant_values=(np.nan)) #_ is previous one
Out[39]: array([ nan,   5.,   5.,   4.,   4.,   6.,   6.,   8.,   8.,  nan])
于 2017-12-01T07:52:30.833 回答