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
2
thumb_down
0
chat_bubble_outline
0
Comment
auto_stories Bi-column layout
settings

Getting indices of N minimum 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 miniumum 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 smallest values:

n = 4

x = np.array([9,3,4,8,7,2,5,6])
min_indices = np.argpartition(x,n-1)[:n]
min_values = x[min_indices]
sorted_min_indices = min_indices[np.argsort(min_values)]
sorted_min_values = x[sorted_min_indices]
print('indices of min values:', min_indices)
print('min values:', min_values)
print('sorted indices of min values:', sorted_min_indices)
print('sorted min values:', sorted_min_values)
indices of min values: [1 5 2 6]
min values: [3 2 4 5]
sorted indices of min values: [5 1 2 6]
sorted min values: [2 3 4 5]

Explanation

The method argpartition(~) returns the following:

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

Here, n-1=3 means that all values from index 0 and up to and including index 2 of the returned array will be guaranteed to be smaller than the value at index 3. This means that values at index 1, 5 and 2, which are 3, 2 and 4 are smaller than the value at index 6, which is 5.

We then use slicing syntax to extract the first 4 values from this indices:

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

The four numbers here represent the indices of the four smallest values in the original array x. However, the trap here is that they are not indices of the sorted smallest values - this is clear when we extract the actual values:

min_values = x[min_indices]
min_values
array([3, 2, 4, 5])

As you can see, the smallest values are not sorted.

In a more practical setting, we often want the indices of smallest values that are sorted in ascending order. We can do this like so:

sorted_min_indices = min_indices[np.argsort(min_values)]
sorted_min_indices
array([5, 1, 2, 6])

Here, we are first using NumPy's argsort(~) method to obtain the indices of the minimum values sorted in ascending order:

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

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

min_indices[np.argsort(min_values)]
array([5, 1, 2, 6])

Two-dimensional arrays

The case covered above is for one-dimensional arrays. To extend this to two-dimensional arrays, we need to leverage fancy indexing:

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]
])

min_indices = np.argpartition(x,n-1)[:,:n]
min_values = extract_with_indices(x, min_indices)
sorted_min_indices = extract_with_indices(min_indices, np.argsort(min_values))
sorted_min_values = extract_with_indices(x, sorted_min_indices)

print("min_indices\n", min_indices)
print("min_values\n", min_values)
print("sorted_min_indices\n", sorted_min_indices)
print("sorted_min_values\n", sorted_min_values)
min_indices
[[5 0 3 1]
[3 0 5 6]]
min_values
[[4 2 5 6]
[2 3 4 5]]
sorted_min_indices
[[0 5 3 1]
[3 0 5 6]]
sorted_min_values
[[2 4 5 6]
[2 3 4 5]]

To understand what extract_with_indices(~) does, check our article here.

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
2
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!