I have a 2 dimensional NumPy array. I know how to get the maximum values over axes:
我有一个2维NumPy数组。我知道如何获得轴上的最大值:
>>> 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? So I would like as output array([1,1,0])
如何获得最大元素的索引?所以我想作为输出数组([1,1,0])
4 个解决方案
#1
93
>>> a.argmax(axis=0)
array([1, 1, 0])
#2
78
>>> 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
#3
25
argmax()
will only return the first occurrence for each row. http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html
argmax()只返回每行的第一个匹配项。 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坐标列表:
x_y_coords = zip(indices[0], indices[1])
#4
5
v = alli.max()
index = alli.argmax()
x, y = index/8, index%8
#1
93
>>> a.argmax(axis=0)
array([1, 1, 0])
#2
78
>>> 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
#3
25
argmax()
will only return the first occurrence for each row. http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html
argmax()只返回每行的第一个匹配项。 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坐标列表:
x_y_coords = zip(indices[0], indices[1])
#4
5
v = alli.max()
index = alli.argmax()
x, y = index/8, index%8