How to Use np.argsort in NumPy: Syntax and Examples
Use
np.argsort to get the indices that would sort an array. It returns an array of indices that sort the original array in ascending order by default. You can use these indices to reorder the array or related data.Syntax
The basic syntax of np.argsort is:
np.argsort(a, axis=-1, kind='quicksort', order=None)
Where:
a: The input array to sort.axis: The axis along which to sort. Default is the last axis.kind: Sorting algorithm to use (e.g., 'quicksort', 'mergesort', 'heapsort', 'stable').order: When sorting structured arrays, specifies field names to sort by.
python
np.argsort(a, axis=-1, kind='quicksort', order=None)
Example
This example shows how to use np.argsort to get the indices that sort an array, and then use those indices to sort the array.
python
import numpy as np arr = np.array([30, 10, 20]) indices = np.argsort(arr) sorted_arr = arr[indices] print('Original array:', arr) print('Indices that sort the array:', indices) print('Sorted array using indices:', sorted_arr)
Output
Original array: [30 10 20]
Indices that sort the array: [1 2 0]
Sorted array using indices: [10 20 30]
Common Pitfalls
One common mistake is expecting np.argsort to return the sorted array itself. Instead, it returns the indices that would sort the array. You must use these indices to reorder the array.
Another pitfall is not specifying the correct axis when working with multi-dimensional arrays, which can lead to unexpected results.
python
import numpy as np arr = np.array([30, 10, 20]) # Wrong: expecting argsort to return sorted array sorted_wrong = np.argsort(arr) print('Wrong output:', sorted_wrong) # This is indices, not sorted values # Right: use indices to sort sorted_right = arr[np.argsort(arr)] print('Correct sorted array:', sorted_right)
Output
Wrong output: [1 2 0]
Correct sorted array: [10 20 30]
Quick Reference
| Parameter | Description | Default |
|---|---|---|
| a | Input array to sort | Required |
| axis | Axis along which to sort | -1 (last axis) |
| kind | Sorting algorithm ('quicksort', 'mergesort', 'heapsort', 'stable') | 'quicksort' |
| order | Field names for structured arrays | None |
Key Takeaways
np.argsort returns indices that would sort an array, not the sorted array itself.
Use the returned indices to reorder the original array or related data.
Specify the axis parameter carefully when sorting multi-dimensional arrays.
Common sorting algorithms include 'quicksort', 'mergesort', and 'heapsort'.
For structured arrays, use the order parameter to sort by specific fields.