xirururu xirururu - 2 months ago 10
Python Question

How to return the indices of maximum value from an array with python?

I have an array and I want to find the indices of the maximum values.

For example:

myarray = np.array([1,8,8,3,2])


I want to get the result:
[1,2]
, how can I do that?

(Actually I tried
np.argmax(myarray)
, but it only return the first occurrence
[1]
)

Answer

Given:

>>> myarray = np.array([1,8,8,3,2])

You can do:

>>> np.where(myarray==myarray[np.argmax(myarray)])
(array([1, 2]),)

or,

>>> np.where(myarray==max(myarray))
(array([1, 2]),)

or,

>>> np.nonzero(myarray==max(myarray))
(array([1, 2]),)