Home > Enterprise >  Does np.argmax return the first maximal?
Does np.argmax return the first maximal?

Time:07-13

Does np.argmax return the index of the first maximal element always?

Let a = np.array([1, 3, -7, ...]) be a 1D-array with several maximal elements, say at indices 10, 20 and 30. Numpy seems to return systematically 10 instead of 20 or 30, but I could not find information about this behavior in the documentation, and I could not find the implementation details in the source code. Does anybody know?

CodePudding user response:

Yes, this is actually explicited in the numpy.argmax documentation:

Notes

In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned.

CodePudding user response:

No it only outputs the first occurrence but you can use np.argsort to get n top maximum:

np.argsort(your_array)[-n:] #the top n indexes

i.e.:

n=2
a = np.array([1,2,3,3,-1])
np.argsort(a)[-n:]
>array([2, 3], dtype=int64) #elements at index 2 and 3 in array a (3, 3) have the top max values 
  • Related