James
James

Reputation: 425

Finding the positions of the max element in a numpy array if there are more than one

Just wondering how to find the index of where the maximums are if there are more than one of them?

At the moment i was doing:

max = np.amax(V)
position = V.tolist().index(max)

But say we have V = [0,1,2,5,2,5,3] We will get max = 5 position = 3 (but not 5?)

Can anyone help? Thanks

Upvotes: 1

Views: 122

Answers (1)

behzad.nouri
behzad.nouri

Reputation: 78021

You may use np.nonzero to find indices which are equal to maximum value:

>>> a
array([2, 5, 4, 4, 4, 2, 1, 1, 2, 2, 5, 4, 1, 4, 0, 0, 5, 1, 4, 1])
>>> np.nonzero(a == a.max())[0]
array([ 1, 10, 16])
>>> a[_]
array([5, 5, 5])

Upvotes: 3

Related Questions