NumPy Tutorial NumPy Statistics NumPy References

NumPy - sort() function



The NumPy sort() function returns a sorted copy of the specified array.

Syntax

numpy.sort(a, axis=-1, kind=None, order=None)

Parameters

a Required. Specify the array (array_like) to be sorted.
axis Optional. Specify the axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis.
kind Optional. Specify sorting algorithm. It can take values from {'quicksort', 'mergesort', 'heapsort', 'stable'}. Default: 'quicksort'
order Optional. Specify string or list of strings containing fields. When a is an array with fields defined, this argument specifies the order in which the fields need to the compared.

Return Value

Returns a sorted array (ndarray) of the same type and shape as a.

Example:

In the example below, sort() function is used to sort elements of a 2-D array. As the axis parameter is not provided, the sorting is done along the last axis (row-wise).

import numpy as np
Arr = np.array([[1,20,5],[21, 4, 3],[11, 5, 50]])
SortedArr = np.sort(Arr)

print("Original Array:")
print(Arr)
print("\nSorted Array:")
print(SortedArr)

The output of the above code will be:

Original Array:
[[ 1 20  5]
 [21  4  3]
 [11  5 50]]

Sorted Array:
[[ 1  5 20]
 [ 3  4 21]
 [ 5 11 50]]

Example: using sort() with axis parameter

To sort the array column-wise, axis parameter can be set to 0.

import numpy as np
Arr = np.array([[1,20,5],[21, 4, 3],[11, 5, 50]])
SortedArr = np.sort(Arr, axis=0)

print("Original Array:")
print(Arr)
print("\nSorted Array:")
print(SortedArr)

The output of the above code will be:

Original Array:
[[ 1 20  5]
 [21  4  3]
 [11  5 50]]

Sorted Array:
[[ 1  4  3]
 [11  5  5]
 [21 20 50]]

Example: using sort() with axis=None

When axis=None is used, the array is flattened before sorting as shown in the example below.

import numpy as np
Arr = np.array([[1,20,5],[21, 4, 3],[11, 5, 50]])
SortedArr = np.sort(Arr, axis=None)

print("Original Array:")
print(Arr)
print("\nSorted Array:")
print(SortedArr)

The output of the above code will be:

Original Array:
[[ 1 20  5]
 [21  4  3]
 [11  5 50]]

Sorted Array:
[ 1  3  4  5  5 11 20 21 50]

Example: using sort() with order parameter

The order can be used to specify the column priority for sorting. Consider the example below:

import numpy as np
datatype = [("name", "S10"), ("age", int)]
values =  [("John", 25),("Marry", 23), ("Adam", 30)]
Arr = np.array(values, dtype = datatype)

#sort the array based on "age" column
SortedArr = np.sort(Arr, order = "age")

print("Original Array:")
print(Arr)
print("\nSorted Array:")
print(SortedArr)

The output of the above code will be:

Original Array:
[('John', 25) ('Marry', 23) ('Adam', 30)]

Sorted Array:
[('Marry', 23) ('John', 25) ('Adam', 30)]

❮ NumPy - Functions