Obtaining the index of the maximum value in a NumPy array is possible with the np.argmax function. However, for retrieving the indices of multiple maximum values, this article explores alternative approaches.
Recent NumPy versions (1.8 onward) feature the argpartition function, which can retrieve indices according to a specified condition. To obtain the indices of the n largest elements, use this function with a negative argument for n, indicating a descending sort.
>>> a = np.array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0]) # Sample array >>> ind = np.argpartition(a, -4)[-4:] # Indices of top 4 largest elements
Unlike argsort, argpartition operates linearly in the worst case, but it does not return sorted indices. To sort them, utilize np.argsort on the partitioned array:
>>> sorted_ind = ind[np.argsort(a[ind])]
Alternatively, leverage the advanced indexing capabilities of NumPy:
>>> descending_order = np.argsort(a)[::-1] # Indices of elements in descending order >>> top_n = descending_order[:n] # Top n indices
Customized solutions also exist, such as:
The above is the detailed content of How to Efficiently Find the Indices of the Top N Largest Values in a NumPy Array?. For more information, please follow other related articles on the PHP Chinese website!