【问题标题】:How to get the position in a certain percentile range of 2-d array with np.NAN in it如何在其中包含 np.NAN 的二维数组的某个百分位范围内获得位置
【发布时间】:2016-05-29 09:01:48
【问题描述】:

这是我的问题。
这里有一些背景介绍:

  • a 是一个二维 numpy 数组,大小为 (50,50)
  • a 中的一些元素是 np.NAN,其他元素有其有限值。

我的目标

获取a百分位范围(70, 80)内每个元素的数组索引

我的尝试

  1. 过滤 a

    中的 np.NAN
    a_noNaN = np.array([0,])
    
    for i in range(0,a.shape[0],1):
     for j in range(0,a.shape[1],1):
         if (np.isnan(a[i,j]) == False):
            a_noNaN       = np.append(a_noNaN,a[i,j])
    
    a_noNaN = a_noNaN[1:] ## the first element "0" is redundant
    
  2. 对数据进行排序并确定取值范围

    a_noNaN_sort = np.sort(a_noNaN)
    a_70 = np.percentile(a_noNaN, 70)
    a_80 = np.percentile(a_noNaN, 80)
    
  3. 获取该值范围内的数组索引

    k = 0
    indice    = np.array([(i, j) for i in xrange(a.shape[0]) for j in xrange(a.shape[1])])
    indice_in = np.zeros_like(indice)
    for t in range(0,indice.shape[0],1):
        for i in range(a.shape[0]):
            for j in range(a.shape[1]):
                if ((a[i,j]<a_80)& ((a[i,j]>a_70))):
                    indice_in[t] = indice[t]
    

我不知道我的方法是对是错。
我可以使用任何更简单的功能来完成工作吗?
任何建议将不胜感激!ヽ(✿゚▽゚)ノ

【问题讨论】:

    标签: python arrays python-2.7 numpy statistics


    【解决方案1】:

    您可以使用 numpy 函数 nanpercentile 来避免考虑 nan

    a_70 = np.nanpercentile(a, 70)
    a_80 = np.nanpercentile(a, 80)
    

    要查找两个百分位数之间的所有元素,您可以使用 numpy 的布尔索引

    bool_indexes = np.logical_and(a > a_70, a < a_80)
    indexes = np.nonzero(bool_indexes)
    

    indexes 将是一个二维数组,其中包含值 a_70a_80 之间的所有元素的索引

    执行的简单演示

    # create a random (20x20) matrix
    a = np.random.randn(20,20)
    a_70 = np.nanpercentile(a, 70)
    a_80 = np.nanpercentile(a, 80)
    bool_indexes = np.logical_and(a > a_70, a < a_80)
    indexes = np.nonzero(bool_indexes)
    print indexes
    
    (array([ 0,  0,  0,  1,  2,  3,  3,  3,  5,  6,  6,  7,  7,  7,  7,  8,  8,
            8,  8,  9, 10, 11, 11, 11, 11, 12, 12, 13, 14, 14, 14, 16, 16, 16,
           16, 17, 19, 19, 19, 19]), 
     array([ 3, 10, 16, 11,  8,  7, 10, 11,  8,  0, 11, 10, 11, 17, 19, 10, 11,
           15, 19, 17,  0,  0,  1,  8, 10,  2,  8, 19, 10, 12, 17,  0,  1,  6,
           14,  6,  3,  4,  5,  7]))
    

    【讨论】:

    • OP:请注意,您可能会发现 bool_indexes 是您真正需要的全部
    • 感谢您的回答! np.logical_and 比我的尝试更好!
    猜你喜欢
    • 2019-03-01
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    • 2021-02-25
    • 1970-01-01
    • 2011-02-12
    • 2016-04-11
    相关资源
    最近更新 更多