search
Search
Login
Math ML Join our weekly DS/ML newsletter
menu
menu search toc more_vert
Robocat
Guest 0reps
Thanks for the thanks!
close
chevron_left Cookbooks
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
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
help Ask a question
Share on Twitter
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
A
A
brightness_medium
share
arrow_backShare
Twitter
Facebook
chevron_left Cookbooks
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
1
thumb_down
0
chat_bubble_outline
0
auto_stories new
settings

Getting indices of N minimum values in NumPy

NumPy
chevron_right
Cookbooks
schedule Jul 1, 2022
Last updated
local_offer PythonNumPy
Tags
tocTable of Contents
expand_more

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.

mail
Join our newsletter for updates on new DS/ML comprehensive guides (spam-free)
robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Ask a question or leave a feedback...
thumb_up
1
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!