问题:如何沿一个轴获取numpy数组中最大元素的索引

我有一个二维的NumPy数组。我知道如何获取轴上的最大值:

>>> a = array([[1,2,3],[4,3,1]])
>>> amax(a,axis=0)
array([4, 3, 3])

如何获得最大元素的索引?所以我想作为输出array([1,1,0])

I have a 2 dimensional NumPy array. I know how to get the maximum values over axes:

>>> a = array([[1,2,3],[4,3,1]])
>>> amax(a,axis=0)
array([4, 3, 3])

How can I get the indices of the maximum elements? I would like as output array([1,1,0]) instead.


回答 0

>>> a.argmax(axis=0)

array([1, 1, 0])
>>> a.argmax(axis=0)

array([1, 1, 0])

回答 1

>>> import numpy as np
>>> a = np.array([[1,2,3],[4,3,1]])
>>> i,j = np.unravel_index(a.argmax(), a.shape)
>>> a[i,j]
4
>>> import numpy as np
>>> a = np.array([[1,2,3],[4,3,1]])
>>> i,j = np.unravel_index(a.argmax(), a.shape)
>>> a[i,j]
4

回答 2

argmax()将仅返回每一行的第一个匹配项。 http://docs.scipy.org/doc/numpy/reference/generation/numpy.argmax.html

如果您需要对整形阵列执行此操作,则此方法比unravel

import numpy as np
a = np.array([[1,2,3], [4,3,1]])  # Can be of any shape
indices = np.where(a == a.max())

您还可以更改条件:

indices = np.where(a >= 1.5)

上面以您要求的形式为您提供了结果。另外,您可以通过以下方式将其转换为x,y坐标列表:

x_y_coords =  zip(indices[0], indices[1])

argmax() will only return the first occurrence for each row. http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html

If you ever need to do this for a shaped array, this works better than unravel:

import numpy as np
a = np.array([[1,2,3], [4,3,1]])  # Can be of any shape
indices = np.where(a == a.max())

You can also change your conditions:

indices = np.where(a >= 1.5)

The above gives you results in the form that you asked for. Alternatively, you can convert to a list of x,y coordinates by:

x_y_coords =  zip(indices[0], indices[1])

回答 3

v = alli.max()
index = alli.argmax()
x, y = index/8, index%8
v = alli.max()
index = alli.argmax()
x, y = index/8, index%8

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