3
Could someone explain to me how the function works argmin()
and argmax()
of Numpy in a simple and didactic way?
3
Could someone explain to me how the function works argmin()
and argmax()
of Numpy in a simple and didactic way?
4
The functions argmax and argmin return, respectively, the indices of the highest and lowest value of an array. A caveat is that if two equal values are greater (or smaller), they return only the index of the first one. Given an array:
a = numpy.array([[0, 10, 2],
[11, 4, 5]])
Use numpy.argmax(a)
returns the index of the highest array value a
as if the array is in the 1D form, that is, of the array.flatten()
.
>>> numpy.argmax(a)
3
>>> a.flatten()
array([ 0, 10, 2, 11, 4, 5])
>>> numpy.argmax(a.flatten())
3
>>> a.flatten()[3] #retorna o maior valor
11
If the array is 2D (an array), it is possible to pick the index of the highest value of each list (i.e., each row) from the matrix using axis=1
.
>>> index = numpy.argmax(a, axis=1)
>>> index
array([1, 0])
>>> [a[i][index[i]] for i in range(0,a.shape[0])] #retorna os maiores valores de cada linha
[10, 11]
Or, with axis = 0
, of each column of the matrix.
>>> index = numpy.argmax(a, axis=0)
>>> index
array([1, 0, 1])
>>> [a[index[i]][i] for i in range(0,a.shape[1])] #maior valor de cada coluna
[11, 10, 5]
One last observation is that for an array ND, it is possible to return the exact index in the form of the array by:
>>> a = numpy.array([[ [1, 2, 3],[4,100,6]], [[7,8,9],[10,11,12]]])
>>> a.shape #Forma de a
(2, 2, 3)
>>> ind = numpy.unravel_index(numpy.argmax(a, axis=None), a.shape)
>>> ind
(0, 1, 1)
>>> a[ind]
100
The use of argmin
is analogous to argmax
.
Obg Alex!!!! For help and patience...
Browser other questions tagged python-3.x numpy
You are not signed in. Login or sign up in order to post.
What I’d like to understand?
– Maniero
what purpose this function serves, in a simple and didactic way of understanding for a beginner
– giunior_candido
pfvr if you can help grateful
– giunior_candido
I do not see this question as broad, and I think the 4 votes received could be rethought.
– gato