python - 沿轴计算多维数组中某个值的百分位等级

标签 python pandas numpy scipy python-xarray

我有一个 3D 维数组。

>>> M2 = np.arange(24).reshape((4, 3, 2))
>>> print(M2)
array([[[ 0,  1],
        [ 2,  3],
        [ 4,  5]],

       [[ 6,  7],
        [ 8,  9],
        [10, 11]],

       [[12, 13],
        [14, 15],
        [16, 17]],

       [[18, 19],
        [20, 21],
        [22, 23]]])

我想计算沿轴 = 0 的特定值的百分位等级。

例如。如果值 = 4,则预期输出为:
[[0.25, 0.25],
 [0.25, 0.25],
 [0.25, 0.0]]

其中 [0][0] 处的 0.25 是 [0, 6, 12, 18] 等中 4 的百分位等级。

如果值 = 2.5,则预期输出为:
[[0.25, 0.25],
 [0.25, 0.0],
 [0.0, 0.0]]

我正在考虑使用 scipy.stats.percentileofscore但这似乎不适用于多维数组。

- - - - - - - - - - - - - - 编辑 - - - - - - - - - - - ------

被埃文的评论启发了。我想出了一个使用 scipy.stats.percentileofscore 的解决方案.
percentile_rank_lst = []
for p in range(M2.shape[1]):
    for k in range(M2.shape[2]):
        M2_ = M2[:, p, k]
        percentile_rank = (stats.percentileofscore(M2_, 4)) / 100
        percentile_rank_lst.append(percentile_rank)

percentile_rank_nparr = np.array(percentile_rank_lst).reshape(M2.shape[1], M2.shape[2])
print(percentile_rank_nparr)

输出是:
array([[0.25, 0.25],
 [0.25, 0.25],
 [0.25, 0.0]])

最佳答案

我认为这可以完成工作:

def get_percentile(val, M=M2, axis=0):
    return (M > val).argmax(axis)/ M.shape[axis]

get_percentile(4)
#array([[0.25, 0.25],
#       [0.25, 0.25],
#       [0.25, 0.  ]])

get_percentile(2.5)
#array([[0.25, 0.25],
#       [0.25, 0.  ],
#       [0.  , 0.  ]])

关于python - 沿轴计算多维数组中某个值的百分位等级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59167498/

相关文章:

python - 我们可以将部分 css 文件包含到模板文件中吗?

python - 将列添加到常规数据帧中的日期时间索引数据帧

python - pandas 最终排名状态

python - Windows 和 Ubuntu 之间 Numpy 数组的内存使用差异

python - Selenium Firefox webdriver 适用于从 Ubuntu 构建的图像,但不适用于从 Debian 构建的图像

python - mplfinance 中是否有 plt.scatter 的等价物?如何在mplfinance中绘制数据点?

python - groupby后如何设置聚合?

python - Cython 程序比普通 Python 慢(10M 选项 3.5s vs 3.25s Black Scholes)——我错过了什么?

python - 替换 numpy 数组中包含 NaN 的值

Python 多线程和 PostgreSQL