Non-mutating sorting
You need sorted values while preserving the original ndarray for later computations.
NumPy · Function
Returns a sorted copy of an array. It can sort along an axis, flatten before sorting, choose an algorithm, preserve equal-value order, and optionally sort descending.
np.sort returns a sorted copy of array-like input. By default it sorts along the last axis using quicksort; choose axis=None to flatten first, select a sorting algorithm with kind, control structured-array field priority with order, and request stable or descending ordering with the corresponding keyword options.
numpy.sort(a, axis=-1, kind=None, order=None, *, stable=None, descending=<no value>)| Name | Type | Description |
|---|---|---|
a | array_like | Array to be sorted. |
axis | int or None, optional | Axis along which to sort; None flattens the array before sorting. Default: -1. |
kind | {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional | Sorting algorithm. Options are 'quicksort', 'mergesort', 'heapsort', and 'stable'; default: 'quicksort'. |
order | str or list of str, optional | For arrays with fields, names the fields to compare in priority order. |
stable | bool, optional | Whether equal values retain relative order; internally selects kind='stable'. |
descending | bool, optional | Whether to sort descending; False or None sorts ascending. |
sorted_array — ndarray: Array of the same type and shape as a.
import numpy as np
values = np.array([[3, 1, 2], [6, 4, 5]])
print(np.sort(values, axis=1))
# [[1 2 3]
# [4 5 6]]Sort each row while returning a separate array; the input remains unchanged.
You need sorted values while preserving the original ndarray for later computations.
You need each row, column, or another dimension sorted independently.
You need deterministic ordering for records with equal comparison keys.
np.sort creates and returns a sorted copy, so the original array is not modified. With the default axis=-1, sorting occurs along the last axis.
Follow-up: How would you sort every element globally? Use axis=None, which flattens the array before sorting.
kind selects the sorting algorithm from quicksort, mergesort, heapsort, or stable. The documented default is quicksort.
Follow-up: How can you preserve the order of equal values? Set stable=True, which internally selects kind='stable'.
For structured arrays, order specifies which named fields are compared first, second, and so on. The result remains an ndarray with the same type and shape as the input.
Follow-up: How can you sort in descending order in the current stable API? Pass descending=True; NaNs still sort to the end.
numpy.argsortnumpy.ndarray.sortnumpy.lexsortnumpy.searchsorted