numpy.sort#

numpy.sort(a, axis=-1, kind=None, order=None, *, stable=None, descending=<no value>)[source]#

Return a sorted copy of an array.

Parameters:
aarray_like

Array to be sorted.

axisint or None, optional

Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis.

kind{‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, optional

Please use the stable parameter instead. This argument is retained for backwards compatibility and provides no additional control. ‘quicksort’ and ‘heapsort’ are equivalent to stable=False, while ‘mergesort’ and ‘stable’ are equivalent to stable=True.

orderstr or list of str, optional

When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.

stablebool, optional

Sort stability. If True, the returned array will maintain the relative order of a values which compare as equal. If False or None, this is not guaranteed. Internally, this option selects kind='stable'. Default: None.

New in version 2.0.0.

descendingbool, optional

Sort order. If True, the returned array will be sorted in descending order. If False or None, the returned array will be sorted in ascending order. Values that are NaN are sorted to the end for both orders. Default: None.

New in version 2.5.0.

Returns:
sorted_arrayndarray

Array of the same type and shape as a.

See also

ndarray.sort

Method to sort an array in-place.

argsort

Indirect sort.

lexsort

Indirect stable sort on multiple keys.

searchsorted

Find elements in a sorted array.

partition

Partial sort.

Notes

NumPy uses different sorting algorithms depending on whether the sort is stable and which data types are used. These are characterized by their worst case performance, work space size, and whether they are stable. A stable sort keeps items with the same key in the same relative order. NumPy chooses between three algorithms:

stable

algorithm

worst case

work space

note

no

Introsort

O(n*log(n))

0

yes

Timsort

O(n*log(n))

~n/2

yes

Radix sort

O(n)

n

bools and narrow integers [1]

For performance, sort makes a temporary copy if needed to make the data contiguous in memory along the sort axis. For even better performance and reduced memory consumption, ensure that the array is already contiguous along the sort axis.

The sort order for complex numbers is lexicographic. If both the real and imaginary parts are non-nan then the order is determined by the real parts except when they are equal, in which case the order is determined by the imaginary parts.

Previous to numpy 1.4.0 sorting real and complex arrays containing nan values led to undefined behaviour. In numpy versions >= 1.4.0 nan values are sorted to the end. The extended sort order is:

  • Real: [R, nan]

  • Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj]

where R is a non-nan real value. Complex values with the same nan placements are sorted according to the non-nan part if it exists. Non-nan values are sorted as before.

NumPy uses introsort by default for unstable sorting.

For stable sorting, NumPy automatically chooses the best stable sorting algorithm for the data type being sorted. It is currently mapped to timsort or radix sort for bools and integer types with a width of 16 bits or less.

For numerical sorts, NaT and NaN always sort to the end of the array for both ascending and descending sort order.

[1]

Radix sort is used for stable sorting of bools and narrow integer types (up to 16 bits). For these it performs better than Timsort.

Examples

>>> import numpy as np
>>> a = np.array([[1,4],[3,1]])
>>> np.sort(a)                # sort along the last axis
array([[1, 4],
       [1, 3]])
>>> np.sort(a, axis=None)     # sort the flattened array
array([1, 1, 3, 4])
>>> np.sort(a, axis=0)        # sort along the first axis
array([[1, 1],
       [3, 4]])

Use the order keyword to specify a field to use when sorting a structured array:

>>> dtype = [('name', 'S10'), ('height', float), ('age', int)]
>>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38),
...           ('Galahad', 1.7, 38)]
>>> a = np.array(values, dtype=dtype)       # create a structured array
>>> np.sort(a, order='height')                        
array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),
       ('Lancelot', 1.8999999999999999, 38)],
      dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])

Sort by age, then height if ages are equal:

>>> np.sort(a, order=['age', 'height'])               
array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38),
       ('Arthur', 1.8, 41)],
      dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])