如何计算Numpy的一维数组的移动(或滚动(如果愿意的话))



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

用移动/滚动百分位数/分位数解释我的含义:

给定数组[1, 5, 7, 2, 4, 6, 9, 3, 8, 10],移动分位数0.5(即移动百分比50%),窗口尺寸3是:

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]是答案。为了使结果串联的长度与输入相同,某些实现插入了NaNNone,而pandas.rolling_quantile()允许通过较小的窗口计算前两个分数值。

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,以进行分位数计算窗口,以对称地包含当前索引。

我们可以使用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.])

为了使其与输入相同的长度,我们可以使用np.concatenate或更容易使用np.pad添加NaNs。因此,对于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])

相关内容

最新更新