问题:numpy数组的argmax返回非固定索引

我正在尝试获取Numpy数组中最大元素的索引。可以使用来完成numpy.argmax。我的问题是,我想在整个数组中找到最大的元素并获取其索引。

numpy.argmax 既可以沿一个轴(不是我想要的)应用,也可以沿扁平数组(这是我想要的一种)应用。

我的问题是,当我想要多维索引时,使用numpy.argmaxwithaxis=None返回平面索引。

我可以divmod用来获取非固定索引,但这很难看。有什么更好的方法吗?

I’m trying to get the indices of the maximum element in a Numpy array. This can be done using numpy.argmax. My problem is, that I would like to find the biggest element in the whole array and get the indices of that.

numpy.argmax can be either applied along one axis, which is not what I want, or on the flattened array, which is kind of what I want.

My problem is that using numpy.argmax with axis=None returns the flat index when I want the multi-dimensional index.

I could use divmod to get a non-flat index but this feels ugly. Is there any better way of doing this?


回答 0

您可以使用以下结果numpy.argmax()

>>> a = numpy.random.random((10, 10))
>>> numpy.unravel_index(a.argmax(), a.shape)
(6, 7)
>>> a[6, 7] == a.max()
True

You could use on the result of numpy.argmax():

>>> a = numpy.random.random((10, 10))
>>> numpy.unravel_index(a.argmax(), a.shape)
(6, 7)
>>> a[6, 7] == a.max()
True

回答 1

np.where(a==a.max())

返回最大元素的坐标,但必须将数组解析两次。

>>> a = np.array(((3,4,5),(0,1,2)))
>>> np.where(a==a.max())
(array([0]), array([2]))

与相比argmax,这将返回等于最大值的所有元素的坐标。argmax仅返回其中之一(np.ones(5).argmax()return 0)。

np.where(a==a.max())

returns coordinates of the maximum element(s), but has to parse the array twice.

>>> a = np.array(((3,4,5),(0,1,2)))
>>> np.where(a==a.max())
(array([0]), array([2]))

This, comparing to argmax, returns coordinates of all elements equal to the maximum. argmax returns just one of them (np.ones(5).argmax() returns 0).


回答 2

要获取所有出现的最大值的非平坦索引,可以使用代替来稍微修改eumiro的答案argwherewhere

np.argwhere(a==a.max())

>>> a = np.array([[1,2,4],[4,3,4]])
>>> np.argwhere(a==a.max())
array([[0, 2],
       [1, 0],
       [1, 2]])

To get the non-flat index of all occurrences of the maximum value, you can modify eumiro’s answer slightly by using argwhere instead of where:

np.argwhere(a==a.max())

>>> a = np.array([[1,2,4],[4,3,4]])
>>> np.argwhere(a==a.max())
array([[0, 2],
       [1, 0],
       [1, 2]])

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。