查找二维数组中最高元素的列表:Python 3

Vik*_*wal 2 python arrays optimization search numpy

我有一个大小为(640X480)的二维数组,如下所示:

[[1.2 , 9.5 , 4.8 , 1.7],
 [5.5 , 8.1 , 7.6 , 7.1],
 [1.4 , 6.9 , 7.8 , 2.2]]     (this is a sample of a 4X3 array)
Run Code Online (Sandbox Code Playgroud)

我必须以最快的方式找到数组中的前 100(或 N)个最高值;所以我需要最优化的代码,它需要最少的处理时间。

因为它是一个巨大的数组,所以如果我只检查每 2 个元素或每 3 或 4 个元素就可以了。

算法的输出应该是一个元组列表,每个元组都是高值元素的二维索引。

例如 9.5 的索引将是 (0,1)

我找到了一个解决方案,但它太慢了:

indexes=[]
for i in range(100):
    highest=-1
    highindex=0.1
    for indi,i in enumerate(array):
        for indj,j in enumerate(i):
            if j>highest and not((indi,indj) in indexes):
                highest= j
                highindex=(indi,indj)
    indexes.append(highindex)
Run Code Online (Sandbox Code Playgroud)

Rom*_*est 6

numpy.argpartitionnumpy.unravel_indexnumpy.column_stack例程:

测试ndarrayarr是改组数组值099形状的(11, 9)
假设我们要查找前 7 个最大值的 2d 索引列表:

In [1018]: arr
Out[1018]: 
array([[36, 37, 38, 39, 40, 41, 42, 43, 44],
       [27, 28, 29, 30, 31, 32, 33, 34, 35],
       [72, 73, 74, 75, 76, 77, 78, 79, 80],
       [ 0,  1,  2,  3,  4,  5,  6,  7,  8],
       [18, 19, 20, 21, 22, 23, 24, 25, 26],
       [45, 46, 47, 48, 49, 50, 51, 52, 53],
       [ 9, 10, 11, 12, 13, 14, 15, 16, 17],
       [90, 91, 92, 93, 94, 95, 96, 97, 98],
       [54, 55, 56, 57, 58, 59, 60, 61, 62],
       [63, 64, 65, 66, 67, 68, 69, 70, 71],
       [81, 82, 83, 84, 85, 86, 87, 88, 89]])

In [1019]: top_N = 7

In [1020]: idx = np.argpartition(arr, arr.size - top_N, axis=None)[-top_N:]

In [1021]: result = np.column_stack(np.unravel_index(idx, arr.shape))

In [1022]: result
Out[1022]: 
array([[7, 2],
       [7, 3],
       [7, 4],
       [7, 5],
       [7, 7],
       [7, 8],
       [7, 6]])
Run Code Online (Sandbox Code Playgroud)

  • @VikhyatAgarwal,这就是答案:您正在测试未初始化或空数组。检查您的数组初始化/填充代码 (2认同)