Home >Backend Development >Python Tutorial >How Can I Find the Indices of the Top N Maximum Values in a NumPy Array?

How Can I Find the Indices of the Top N Maximum Values in a NumPy Array?

Susan Sarandon
Susan SarandonOriginal
2024-12-06 01:38:11839browse

How Can I Find the Indices of the Top N Maximum Values in a NumPy Array?

Finding Multiple Maximum Values with NumPy

NumPy arrays offer various functions for statistical operations, including finding the single maximum value using np.argmax. However, for scenarios where it's necessary to identify the top N maximum values, there's a specific requirement that np.argmax cannot fulfill.

Solution: Utilizing np.argpartition in Newer NumPy Versions

With NumPy versions 1.8 and higher, the np.argpartition function provides a solution for this problem. By employing this function, you can obtain the indices of the N largest elements.

For example, consider an array [1, 3, 2, 4, 5]. To retrieve the indices of the four largest elements:

import numpy as np

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

This will result in the following output:

array([1, 5, 8, 0])
array([4, 9, 6, 9])

where 'ind' represents the indices of the four largest elements, and 'top_four' are the corresponding values.

Sorting the Indices for Ordered Output

If required, you can further sort the indices by invoking np.argsort on the corresponding array elements:

sorted_ind = ind[np.argsort(a[ind])]

This ensures that the top-k elements are obtained in sorted order, with a time complexity of O(n k log k).

The above is the detailed content of How Can I Find the Indices of the Top N Maximum Values in a NumPy Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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