np.argsort
is a NumPy function that returns the indices that would sort an array along a specified axis. It performs an indirect sort on the input array and returns an array of indices that represent the sorted order of the elements. The returned indices can be used to construct a sorted version of the input array.
The values in the sorted indices array returned by np.argsort
represent the indices of the elements in the original array that would arrange the elements in ascending order. In other words, each value in the sorted indices array indicates the position of an element in the sorted order.
Let’s break down the example for better understanding:
import numpy as np
arr = np.array([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5])
# Get the indices that would sort the array
sorted_indices = np.argsort(arr)
print("Original array:", arr)
print("Sorted indices:", sorted_indices)
print("Sorted array:", arr[sorted_indices])
It will return:
- Original array:
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
- Sorted indices:
[1, 3, 6, 0, 9, 4, 8, 10, 2, 7, 5]
- Sorted array:
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
Here’s the breakdown:
- The original array has values
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
. - The sorted indices array indicates the indices of the elements in the original array if it were sorted in ascending order. For example, the smallest element in the original array is at index 1 (
arr[1]
), the second smallest is at index 3 (arr[3]
), and so on. - The sorted array is constructed by using the sorted indices to rearrange the elements of the original array.