如何计算numpy中一维数组的移动(或滚动,如果愿意的话)百分位数/分位数? [英] How to compute moving (or rolling, if you will) percentile/quantile for a 1d array in numpy?

查看:621
本文介绍了如何计算numpy中一维数组的移动(或滚动,如果愿意的话)百分位数/分位数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In pandas, we have pd.rolling_quantile(). And in numpy, we have np.percentile(), but I'm not sure how to do the rolling/moving version of it.

要解释我的意思是移动/滚动百分位数/分位数:

To explain what I meant by moving/rolling percentile/quantile:

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

Given array [1, 5, 7, 2, 4, 6, 9, 3, 8, 10], the moving quantile 0.5 (i.e. moving percentile 50%) with window size 3 is:

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()允许通过较小的窗口来计算前两个分位数.

So [5, 5, 4, 4, 6, 6, 8, 8] is the answer. To make the resulting series the same length as the input, some implementation inserts NaN or None, while pandas.rolling_quantile() allows to compute the first two quantile values by a smaller window.

推荐答案

我们可以使用np.lib.stride_tricks.as_strided创建滑动窗口,将其实现为

We could create the sliding windows with np.lib.stride_tricks.as_strided, implemented as a function as 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填充NaNs或使用np.pad进行填充.因此,对于W=3,它应该是-

To make it of the same length as the input, we could pad NaNs with np.concatenate or easier with np.pad. Hence, for W=3, it would be -

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])

这篇关于如何计算numpy中一维数组的移动(或滚动,如果愿意的话)百分位数/分位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆