search
Search
Login
Unlock 100+ guides
menu
menu
web
search toc
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to
chevron_leftCookbooks
Accessing a value in a 2D arrayAccessing columns of a 2D arrayAccessing rows of a 2D arrayCalculating the determinant of a matrixChecking allowed values for a NumPy data typeChecking if a NumPy array is a view or copyChecking the version of NumPyChecking whether a NumPy array contains a given rowComputing Euclidean distance using NumpyConcatenating 1D arraysConverting array to lowercaseConverting type of NumPy array to stringCreating a copy of an arrayDifference between Python List and Numpy arrayDifference between the methods array_equal and array_equivDifference between the methods mod and fmodDifference between the methods power and float_powerFinding the closest value in an arrayFinding the Index of Largest Value in a Numpy ArrayFinding the Index of Smallest Value in a Numpy ArrayFinding the most frequent value in a NumPy arrayFlattening Numpy arraysGetting constant PiGetting elements from a two dimensional array using two dimensional array of indicesGetting indices of N maximum valuesGetting indices of N minimum valuesGetting the number of columns of a 2D arrayGetting the number of non-zero elements in a NumPy arrayGetting the number of rows of a 2D arrayInitializing an array of onesInitializing an array of zerosInitializing an identity matrixLimiting array values to a certain rangePerforming linear regressionPrinting full or truncated NumPy arrayPrinting large Numpy arrays without truncationRemoving rows containing NaN in a NumPy arrayReversing a NumPy arraySaving NumPy array to a fileShape of Numpy ArraysSorting value of one array according to anotherSuppressing scientific notation
check_circle
Mark as learned
thumb_up
0
thumb_down
0
chat_bubble_outline
0
Comment
auto_stories Bi-column layout
settings

Getting indices of N maximum values in NumPy

schedule Aug 12, 2023
Last updated
local_offer
PythonNumPy
Tags
tocTable of Contents
expand_more
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

To get the indices of N maximum values in NumPy in an optimal way, use the argpartition(~) method.

In short, the argpartition(~) method allows you to select an index by which to partition, and ensures that all values at indices smaller than the value at this index appear before it, and all values at indices larger than this index value appear after it.

Example

To get the indices of the 4 largest values:

n = 4

x = np.array([4,3,7,2,5,6,9,8])
max_indices = np.argpartition(x,-n)[-n:]
max_values = x[max_indices]
sorted_max_indices = max_indices[np.argsort(max_values)[::-1]]
sorted_max_values = x[sorted_max_indices]
print('indices of max values:', max_indices)
print('max values:', max_values)
print('sorted indices of max values:', sorted_max_indices)
print('sorted max values:', sorted_max_values)
indices of max values: [5 2 6 7]
max values: [6 7 9 8]
sorted indices of max values: [6 7 2 5]
sorted max values: [9 8 7 6]

Explanation

The argpartition(~) method here returns the following:

n = 4
x = np.array([4,3,7,2,5,6,9,8])
np.argpartition(x,-n)
array([1, 3, 0, 4, 5, 2, 6, 7])

Here, the second argument takes on the value of -4, which means that all values starting from the last 3 values of the returned array will be guaranteed to be larger than the fourth value from the end. This means that values at indices 2, 6 and 7, which are 7, 9 and 8 are larger than the value at index 5, which is 6.

We then extract the last 4 values using the slicing:

np.argpartition(x,-n)[-n:]
array([5, 2, 6, 7])

These values represent the indices of 4 largest values in the original array x. However, the caveat here is that these are not sorted, which becomes clear when we extract the original values using these indices:

max_indices = np.argpartition(x,-n)[-n:]
max_values = x[max_indices]
max_values
array([6, 7, 9, 8])

As you can see here, the maximum values are not sorted in any way.

In a practical setting, we may want to obtain indices of maximum values are sorted in descending order. We can do this like so:

sorted_max_indices = max_indices[np.argsort(max_values)[::-1]]
sorted_max_indices
array([6, 7, 2, 5])

To break this down, we first use np.argsort(~) to retrieve the indices of the sorted maximum values:

np.argsort(max_values)
array([0, 1, 3, 2])

The problem with this is that argsort(~) only returns the indices of values sorted in ascending order. In our case, we want the indices of values sorted in descending order. Therefore, we reverse the array using the syntax [::-1]:

np.argsort(max_values)[::-1]
array([2, 3, 1, 0])

We then rearrange the our indices of maximum values using this new order:

max_indices[np.argsort(max_values)[::-1]]
array([6, 7, 2, 5])

Two-dimensional case

The case covered above was for one-dimensional case. For two-dimensional arrays, use the following code snippet:

def extract_with_indices(x, idx):
return x[np.arange(x.shape[0])[:, None], idx]

n = 4
x = np.array([
[2,6,9,5,7,4,8],
[3,9,7,2,6,4,5]
])

max_indices = np.argpartition(x,-n)[:,-n:]
max_values = extract_with_indices(x, max_indices)
sorted_max_indices = extract_with_indices(max_indices, np.fliplr(np.argsort(max_values)))
sorted_max_values = extract_with_indices(x, sorted_max_indices)

print("max_indices\n", max_indices)
print("max_values\n", max_values)
print("sorted_max_indices\n", sorted_max_indices)
print("sorted_max_values\n", sorted_max_values)
max_indices
[[1 4 2 6]
[6 4 1 2]]
max_values
[[6 7 9 8]
[5 6 9 7]]
sorted_max_indices
[[2 6 4 1]
[1 2 4 6]]
sorted_max_values
[[9 8 7 6]
[9 7 6 5]]

Note the following:

  • For one-dimensional arrays, we used [::-1] to reverse the array, but for two-dimensional case, we use np.fliplr(~).

  • Refer to this article to understand the logic behind extract_with_indicejs(~).

robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
0
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!