简体   繁体   English

如何返回二维 NumPy 数组中最高和元素的索引?

[英]How to return index of highest sum element in 2D NumPy array?

Suppose I have the following array:假设我有以下数组:

array = numpy.array([[[7.1, 4.5, 2.1], [0.9, 0.6, 10.1]],
                    [[11.0, 5.4, 4.3], [6.7, 0.3, 8.2]]])

I am trying to create a function that allows me to find the element with the highest sum value and return its position in the form (row, column), probably as a tuple.我正在尝试创建一个函数,该函数允许我找到总和值最高的元素并以形式(行、列)返回其位置,可能作为元组。 In this case, the desired output would be (1,0) as the element in the second row, first column has the highest sum value.在这种情况下,所需的输出将是(1,0)作为第二行中的元素,第一列的总和值最高。

This has been my approach, but I can't seem to figure out how to get the output I desire.这是我的方法,但我似乎无法弄清楚如何获得我想要的输出。 I've looked through the NumPy documentation extensively and tried many variations of .max and .where commands.我已经广泛浏览了 NumPy 文档,并尝试了 .max 和 .where 命令的许多变体。

def function(array):
for row in range(len(array)):
    for column in range(len(array[row])):
        total = (array[row, column, 0] + array[row, column, 1] + array[row, column, 2]) 
        array[row, column, 0] = total
        array[row, column, 1] = total
        array[row, column, 2] = total
    return ???

My thought was to reassign the total value to all the elements within each list in the array then use something like numpy.max to give me the position of the maximum value, but that appears to produce an index value outside of the range I'm expecting.我的想法是将总值重新分配给数组中每个列表中的所有元素,然后使用 numpy.max 之类的东西给我最大值的位置,但这似乎产生了超出范围的索引值期待。

Any advice is appreciated!任何建议表示赞赏!

Use np.argmax to find the maximum index and np.unravel_index to convert it to the expected format:使用np.argmax查找最大索引并使用np.unravel_index将其转换为预期格式:

import numpy as np

array = np.array([[[7.1, 4.5, 2.1], [0.9, 0.6, 10.1]],
                  [[11.0, 5.4, 4.3], [6.7, 0.3, 8.2]]])

# sum across last index to find values
ssum = array.sum(-1)

# find the index using argmax, un-ravel it
res = np.unravel_index(ssum.argmax(), ssum.shape)
print(res)

Output输出

(1, 0)

You need first compute sum then find max and find index like below:您需要先计算总和,然后找到最大值并找到索引,如下所示:

>>> import numpy as np
>>> arr = np.array([[[7.1, 4.5, 2.1], [0.9, 0.6, 10.1]],
...                    [[11.0, 5.4, 4.3], [6.7, 0.3, 8.2]]])

>>> sum_3d = np.sum(arr,axis = 2)
>>> sum_3d
array([[13.7, 11.6],
       [20.7, 15.2]])

>>> max_sum_3d = np.amax(sum_3d)
>>> max_sum_3d
20.7

>>> np.argwhere( sum_3d == max_sum_3d )
array([[1, 0]])

# If you want output as tuple you can try this
>>> idx = np.argwhere( sum_3d == max_sum_3d )
>>> tuple(idx[0])
(1,0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM