NumPy ndarray.argsort()
The numpy.ndarray.argsort()
method returns the indices that would sort an array along the specified axis.
This is useful for indirect sorting where you need to access elements in sorted order without modifying the original array.
Syntax
ndarray.argsort(axis=-1, kind=None, order=None)
Parameters
Parameter | Type | Description |
---|---|---|
axis | int, optional | The axis along which to sort. Default is -1 (last axis). |
kind | {‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, optional | Sorting algorithm to use. Default is quicksort . |
order | list of str, optional | Only used when sorting structured arrays. Specifies the field(s) to sort by. |
Return Value
Returns an array of integer indices indicating the order that sorts the array. The returned indices can be used to reorder elements of the original array.
Examples
1. Sorting a 1D Array with argsort()
Here, we create a 1D NumPy array and use argsort()
to get the indices that would sort the array.
import numpy as np
# Create a 1D NumPy array
arr = np.array([42, 17, 23, 56, 9])
# Get the indices that would sort the array
sorted_indices = arr.argsort()
# Print results
print("Original array:", arr)
print("Sorted indices:", sorted_indices)
print("Sorted array:", arr[sorted_indices]) # Using indices to sort
Output:
Original array: [42 17 23 56 9]
Sorted indices: [4 1 2 0 3]
Sorted array: [ 9 17 23 42 56]
The result shows the indices that would sort the array. Using arr[sorted_indices]
, we obtain the sorted array.
2. Sorting a 2D Array Along an Axis
Sorting a 2D array along different axes using argsort()
.
# Create a 2D NumPy array
arr = np.array([[30, 20, 50],
[10, 40, 60]])
# Get the indices that would sort along columns (axis=0)
sorted_indices_axis0 = arr.argsort(axis=0)
# Get the indices that would sort along rows (axis=1)
sorted_indices_axis1 = arr.argsort(axis=1)
# Print results
print("Original array:\n", arr)
print("Sorted indices along axis 0:\n", sorted_indices_axis0)
print("Sorted indices along axis 1:\n", sorted_indices_axis1)
Output:
Original array:
[[30 20 50]
[10 40 60]]
Sorted indices along axis 0:
[[1 0 0]
[0 1 1]]
Sorted indices along axis 1:
[[1 0 2]
[0 1 2]]
For axis=0
, sorting happens column-wise, and for axis=1
, sorting occurs row-wise.
3. Using a Stable Sorting Algorithm
We specify kind='stable'
to maintain the relative order of equal elements.
# Create an array with repeated elements
arr = np.array([20, 10, 30, 20, 10])
# Use argsort with stable sorting
sorted_indices_stable = arr.argsort(kind='stable')
# Print results
print("Original array:", arr)
print("Sorted indices:", sorted_indices_stable)
print("Sorted array:", arr[sorted_indices_stable])
Output:
Original array: [20 10 30 20 10]
Sorted indices: [1 4 0 3 2]
Sorted array: [10 10 20 20 30]
Since we used stable
sorting, the relative order of duplicate values (20 and 10) is preserved.
4. Sorting a Structured Array Using the order
Parameter
Sorting an array of structured data by a specific field.
# Create a structured NumPy array
dtype = [('name', 'U10'), ('age', int)]
arr = np.array([('Alice', 25), ('Bob', 22), ('Charlie', 30)], dtype=dtype)
# Get sorted indices by age
sorted_indices = arr.argsort(order='age')
# Print results
print("Original array:\n", arr)
print("Sorted indices:", sorted_indices)
print("Sorted array:\n", arr[sorted_indices])
Output:
Original array:
[('Alice', 25) ('Bob', 22) ('Charlie', 30)]
Sorted indices: [1 0 2]
Sorted array:
[('Bob', 22) ('Alice', 25) ('Charlie', 30)]
Sorting is based on the age
field of the structured array.