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 argpartition
method.
For instance, we write:
import numpy as np
a = np.array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0])
ind = np.argpartition(a, -4)[-4:]
print(ind)
We call np.array
with a list to create a Numpy array.
Then we call np.argpartition
with a
and -4 and [-4:]
to get the top 4 elements in the array.
Therefore, ind
is [1 5 8 0]
.
Conclusion
To get indices of N maximum values in a Python NumPy array, we can use the argpartition
method.