Home > Backend Development > Python Tutorial > How to Efficiently Find the Indices of the Top N Largest Values in a NumPy Array?

How to Efficiently Find the Indices of the Top N Largest Values in a NumPy Array?

Susan Sarandon
Release: 2024-12-25 03:59:08
Original
456 people have browsed it

How to Efficiently Find the Indices of the Top N Largest Values in a NumPy Array?

Identifying Indices of Top N Values in a NumPy Array

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
Copy after login

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])]
Copy after login

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
Copy after login

Customized solutions also exist, such as:

  • Sorting the array and selecting the top n elements
  • Iteratively comparing elements and updating an index list
  • Utilizing the max() function with conditional assignments

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template