How to Use np.sort in NumPy for Sorting Arrays
Use
np.sort(array, axis=-1, kind='quicksort', order=None) to sort a NumPy array. It returns a sorted copy of the array without changing the original. You can specify the axis to sort along and the sorting algorithm.Syntax
The basic syntax of np.sort is:
array: The input array to sort.axis: The axis along which to sort. Default is-1(last axis).kind: Sorting algorithm to use. Options:'quicksort'(default),'mergesort','heapsort','stable'.order: When sorting structured arrays, specify field names to sort by.
python
np.sort(array, axis=-1, kind='quicksort', order=None)
Example
This example shows how to sort a 2D array along different axes and how the original array remains unchanged.
python
import numpy as np arr = np.array([[3, 1, 2], [6, 4, 5]]) sorted_default = np.sort(arr) # Sort along last axis (axis=1) sorted_axis0 = np.sort(arr, axis=0) # Sort along rows (axis=0) print('Original array:') print(arr) print('\nSorted along last axis (axis=1):') print(sorted_default) print('\nSorted along first axis (axis=0):') print(sorted_axis0)
Output
Original array:
[[3 1 2]
[6 4 5]]
Sorted along last axis (axis=1):
[[1 2 3]
[4 5 6]]
Sorted along first axis (axis=0):
[[3 1 2]
[6 4 5]]
Common Pitfalls
Modifying the original array: np.sort returns a sorted copy and does not change the original array. To sort in-place, use array.sort().
Wrong axis: Sorting along the wrong axis can lead to unexpected results. Always check the shape and axis.
Structured arrays: When sorting structured arrays, you must specify the order parameter to sort by fields.
python
import numpy as np arr = np.array([3, 1, 2]) sorted_arr = np.sort(arr) print('Original array after np.sort:', arr) arr.sort() # In-place sort print('Original array after arr.sort():', arr)
Output
Original array after np.sort: [3 1 2]
Original array after arr.sort(): [1 2 3]
Quick Reference
| Parameter | Description | Default |
|---|---|---|
| array | Input array to sort | Required |
| axis | Axis along which to sort (-1 means last axis) | -1 |
| kind | Sorting algorithm: 'quicksort', 'mergesort', 'heapsort', 'stable' | 'quicksort' |
| order | Field names for sorting structured arrays | None |
Key Takeaways
np.sort returns a sorted copy and does not change the original array.
Use the axis parameter to control which dimension to sort along.
Choose the sorting algorithm with the kind parameter for performance or stability.
For in-place sorting, use the array's sort() method instead of np.sort.
Specify order when sorting structured arrays to sort by specific fields.