【问题标题】:Numpy: Find index of second highest value in each row of an ndarrayNumpy:在ndarray的每一行中查找第二高值的索引
【发布时间】:2020-09-18 20:29:24
【问题描述】:

我有一个[10,10] numpy.ndarray。我试图让索引成为每行中第二高的数字。所以对于数组:

[101   0   1   0   0   0   1   1   2   0]
[  0 116   1   0   0   0   0   0   1   0]
[ 1  4 84  2  2  0  2  4  6  1]
[ 0  2  0 84  0  6  0  2  3  0]
[ 0  0  1  0 78  0  0  2  0 11]
[ 2  0  0  1  1 77  5  0  2  0]
[ 1  2  1  0  1  2 94  0  1  0]
[ 0  1  1  0  0  0  0 96  0  4]
[ 1  5  4  3  1  3  0  1 72  4]
[ 0  1  0  0  3  2  0  7  0 82]

预期结果:[8, 2, 8, 5, 9, ...]

有什么建议吗?

【问题讨论】:

  • 您能否更新问题以显示您迄今为止尝试/研究的内容?你被困在哪里了?

标签: python numpy numpy-ndarray


【解决方案1】:

我对一些事情感到困惑,例如:

1 - 如果最高的数字重复,你会认为它是第二高的数字吗?

2 - 如果第二大数字重复,您想知道它在数组中的所有位置还是只知道第一次出现?

无论如何,我的解释有我的解决方案:

import numpy as np

my_array = np.array([[101 ,0 ,1 ,0 ,0 ,0 ,1 ,1 ,2 ,0],
[ 0 ,116 ,1 ,0 ,0 ,0 ,0 ,0 ,1 ,0],
[ 1 ,4 ,84 ,2 ,2 ,0 ,2 ,4 ,6 ,1],
[ 0 ,2 ,0 ,84 ,0 ,6 ,0 ,2 ,3 ,0],
[ 0 ,0 ,1 ,0 ,78 ,0 ,0 ,2 ,0 ,11],
[ 2 ,0 ,0 ,1 ,1 ,77 ,5 ,0 ,2 ,0],
[ 1 ,2 ,1 ,0 ,1 ,2 ,94 ,0 ,1 ,0],
[ 0 ,1 ,1 ,0 ,0 ,0 ,0 ,96 ,0 ,4],
[ 1 ,5 ,4 ,3 ,1 ,3 ,0 ,1 ,72 ,4],
[ 0 ,1 ,0 ,0 ,3 ,2 ,0 ,7 ,0 ,82]])

result = []

for row in my_array:
    second = np.sort(row)[-2] #Finds the second highest number
    i = np.where(row == second) #Looks for where the condition is true
    result.append(i[0][0]) #Appends the first occurence

【讨论】:

    【解决方案2】:

    神奇的numpy.argsort() 函数使这项任务变得非常简单。找到排序后的索引后,获取倒数第二列。

    m = np.array([[101,   0,   1,   0,   0,   0,   1,   1,   2,   0],
                  [  0, 116,   1,   0,   0,   0,   0,   0,   1,   0],
                  [  1,   4,  84,   2,   2,   0,   2,   4,   6,   1],
                  [  0,   2,   0,  84,   0,   6,   0,   2,   3,   0],
                  [  0,   0,   1,   0,  78,   0,   0,   2,   0,  11],
                  [  2,   0,   0,   1,   1,  77,   5,   0,   2,   0],
                  [  1,   2,   1,   0,   1,   2,  94,   0,   1,   0],
                  [  0,   1,   1,   0,   0,   0,   0,  96,   0,   4],
                  [  1,   5,   4,   3,   1,   3,   0,   1,  72,   4],
                  [  0,   1,   0,   0,   3,   2,   0,   7,   0,  82]])
    
    # Get index for the second highest value.
    m.argsort()[:,-2]
    

    输出:

    array([8, 8, 8, 5, 9, 6, 5, 9, 1, 7], dtype=int32)
    

    【讨论】:

      【解决方案3】:

      使用argpartition 可能比argsort

      In [167]: n = 2
      
      In [168]: arr.argpartition(-n)[:,-n]
      Out[168]: array([8, 8, 8, 5, 9, 6, 1, 9, 1, 7], dtype=int32)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-10-10
        • 2021-09-29
        • 2016-05-16
        • 2018-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多