用 python 的分位数索引替换 numpy 数组中的条目

Replacing entries in a numpy array with their quantile index with python

我有一个包含数字的一维 numpy 数组,我希望每个数字都替换为它所属的分位数的索引。

这是我的五分位指数代码:

import numpy as np

def get_quintile_indices( a ):

    result = np.ones( a.shape[ 0 ] ) * 4

    quintiles = [
        np.percentile( a, 20 ),
        np.percentile( a, 40 ),
        np.percentile( a, 60 ),
        np.percentile( a, 80 )
    ]

    for q in quintiles:
        result -= np.less_equal( a, q ) * 1

    return result

a = np.array( [ 58, 54, 98, 76, 35, 13, 62, 18, 62, 97, 44, 43 ] )
print get_quintile_indices( a )

输出:

[ 2.  2.  4.  4.  0.  0.  3.  0.  3.  4.  1.  1.]

你看,我从一个用尽可能高的索引初始化的数组开始,对于每个五分位数切点,从小于或等于五分位数切点的每个条目中减去 1。有一个更好的方法吗?可用于将数字映射到切点列表的内置函数?

首先,我们可以一次性生成那些 quintiles -

quintiles = np.percentile( a, [20,40,60,80] )    

对于获取偏移量的最后一步,我们可以简单地使用 np.searchsorted 这可能是您正在寻找的内置函数,就像这样 -

out = np.searchsorted(quintiles, a)

或者,将循环代码直接转换为矢量化版本将使用 broadcasting,就像这样 -

# Use broadcasting to perform those comparisons in one go.
# Then, simply sum along the first axis and subtract from 4. 
out = 4 - (quintiles[:,None] >=  a).sum(0)

如果quintiles是一个列表,我们需要把它赋值成一个数组,然后使用broadcasting,像这样-

out = 4 - (np.asarray(quintiles)[:,None] >=  a).sum(0)