Anonymous
Anonymous

Reputation: 477

The best way to get the array index number for maximum element in the array

I wish to get the element index that is the highest in the array.

import numpy as np

a = np.array([1,2,3,4])
print(np.where(a==a.max()))

Current output:

(array([3]),)

Expected output: 3

Upvotes: 0

Views: 65

Answers (3)

Nils
Nils

Reputation: 930

You can use np.argmax(). It will return the index of the highest value in your array.

For more deatils on the function here is a link to the documentation.

np.argmax() also works for 2D-arrys:

a = array([[10, 11, 12],
       [13, 14, 15]])

np.argmax(a)
>>> 5

np.argmax(a, axis=0)
>>> array([1, 1, 1])

np.argmax(a, axis=1)
>>> array([2, 2])

Upvotes: 2

Siddharth Narayan
Siddharth Narayan

Reputation: 87

Try this, it will return the value of the largest element in the array

import numpy as np
a = np.array([1,2,3,4])

print(np.argmax(a))

Upvotes: -1

zipa
zipa

Reputation: 27889

Use argmax that returns the indices of the maximum values along an axis:

np.argmax(a)

3

As you don't supply the axis it will return the index of flattened array:

a = np.array([[1, 2, 3, 4], [2, 3, 3, 9]])

np.argmax(a)

7

Upvotes: 2

Related Questions