Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用python将numpy数组中的条目替换为其分位数索引_Python_Performance_Numpy_Vectorization_Quantile - Fatal编程技术网

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

用python将numpy数组中的条目替换为其分位数索引,python,performance,numpy,vectorization,quantile,Python,Performance,Numpy,Vectorization,Quantile,我有一个带有数字的一维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(

我有一个带有数字的一维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 = np.percentile( a, [20,40,60,80] )    
对于获得偏移量的最后一步,我们可以简单地使用,这可能是您所寻找的内置函数,如-

out = np.searchsorted(quintiles, a)
# 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)
out = 4 - (np.asarray(quintiles)[:,None] >=  a).sum(0)
或者,将循环代码直接转换为矢量化版本也可以使用,如下所示-

out = np.searchsorted(quintiles, a)
# 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)
out = 4 - (np.asarray(quintiles)[:,None] >=  a).sum(0)
如果
quintiles
是一个列表,我们需要将其分配为一个数组,然后使用
broadcasting
,如下所示-

out = np.searchsorted(quintiles, a)
# 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)
out = 4 - (np.asarray(quintiles)[:,None] >=  a).sum(0)

应该是
out=np.searchsorted(五分位,a)
。@daign如果我们用
np.percentile(a,[20,40,60,80])
生成
五分位
,那么
五分位
将是一个数组,然后
五分位。searchsorted(a)
。但是是的,如果
quintiles
是一个类似于代码中的列表,那么我们需要使用
np。searchsorted(quintiles,a)
。奇怪的是
np。百分位(a,[20,40,60,80])
没有给我一个数组,而是一个列表。python版本之间有区别吗?我正在使用Python 2.7。3@daign你的NumPy版本是什么?
>>NumPy.version.version'1.6.1'
因为我还在使用Ubuntu 12.04:)