Categories
Python Answers

How to get indices of N maximum values in a Python NumPy array?

Spread the love

Sometimes, we want to get indices of N maximum values in a Python NumPy array.

In this article, we’ll look at how to get indices of N maximum values in a Python NumPy array.

How to get indices of N maximum values in a Python NumPy array?

To get indices of N maximum values in a Python NumPy array, we can use the np.argpartition method.

For instance, we write

a = np.array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0])
ind = np.argpartition(a, -4)[-4:]

to create the a numpy array with

a = np.array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0])

Then we call argpartition with the array a and -4 to get the indices of the top 4 elements from sorted by value at the given index ascending with

np.argpartition(a, -4)[-4:]

Conclusion

To get indices of N maximum values in a Python NumPy array, we can use the np.argpartition method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *