Table of Contents



Introduction

Sorting an array means rearranging the elements into an ascending or descending ordered sequence. In this article, we will examine the NumPy function numpy.sort and the related ndarray object method sort().

The numpy.sort Function

The numpy.sort function returns a sorted copy of an array.

Syntax

The numpy.sort function.

1numpy.sort(a, axis=- 1, kind=None, order=None)
Parameter Required? Default Value Description
a ✔️ Yes NA Array to be sorted.
axis ❌ No -1 Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis.
kind ❌ No None Sorting algorithm. The default is ‘quicksort’.
order ❌ No None When a is an array with fields defined, this argument specifies which fields to compare first, second, etc.
Note

The numpy.sort function returns a sorted copy of the input array. The input array is not modified.

As usual, we begin this section by first importing the NumPy package and creating a few random arrays using the numpy.random.choice function and seeding the PRNG so that results are reproducible by the reader.

1import numpy as np
2R = np.random.RandomState(17) #set a random seed
3a1 = R.choice(10, size=15, replace=True) # 1-D random array
4print(a1)
5a2 = R.choice(10, size=(4,5), replace=True) # 2-D random array
6print(a2)
[1 6 6 9 0 6 4 7 4 7 1 1 9 8 2]

[[3 6 6 9 9]
 [1 5 1 0 5]
 [6 6 2 6 9]
 [8 3 2 1 9]]

Sorting of 1-D arrays

Example

Sort a 1-D array in ascending order using numpy.sort.

1np.sort(a1)
array([0, 1, 1, 1, 2, 4, 4, 6, 6, 6, 7, 7, 8, 9, 9])

What about sorting the 1-D array in descending order? There are no built-in parameters in the numpy.sort function that allow for sorting in descending order. But a few tricks can easily accomplish this.

Example

Sort a 1-D array in descending order using numpy.sort.

1-np.sort(-a1)
array([9, 9, 8, 7, 7, 6, 6, 6, 4, 4, 2, 1, 1, 1, 0])

Alternatively, we can sort in ascending order and then reverse.

Example

Sort a 1-D array in descending order using numpy.sort.

1np.sort(a1)[::-1]
array([9, 9, 8, 7, 7, 6, 6, 6, 4, 4, 2, 1, 1, 1, 0])

Example

Sorted array is a copy of input array.

1print(a1) # unmodified
[1 6 6 9 0 6 4 7 4 7 1 1 9 8 2]

ADVERTISEMENT



Sorting of 2-D arrays

Recall that the default sorting axis is along the last axis (axis=-1). For the case of a 2-D array, this means the sorting is performed along axis=1.

Example

Sort a 2-D array in ascending order using numpy.sort.

1np.sort(a2)
array([[3, 6, 6, 9, 9],
       [0, 1, 1, 5, 5],
       [2, 6, 6, 6, 9],
       [1, 2, 3, 8, 9]])

Observe that the rows of the 2-D array are sorted in ascending order. The sorting is performed along axis=1 (column-wise).

Example

Sort a 2-D array in ascending order along axis=1 using numpy.sort.

1np.sort(a2)
array([[3, 6, 6, 9, 9],
       [0, 1, 1, 5, 5],
       [2, 6, 6, 6, 9],
       [1, 2, 3, 8, 9]])

Observe that the rows of the 2-D array are sorted in ascending order. In plain language, the sorting is performed along axis=1 from smallest to largest.

To sort a 2-D array in descending order along axis=1, we make use of the same tricks like we did for the case of 1-D arrays.

Example

Sort a 2-D array in descending order along axis=1 using numpy.sort.

1-np.sort(-a2) # descending order along axis=1
array([[9, 9, 6, 6, 3],
       [5, 5, 1, 1, 0],
       [9, 6, 6, 6, 2],
       [9, 8, 3, 2, 1]])

Alternatively,

1np.sort(a2)[:,::-1] # descending order along axis=1
array([[9, 9, 6, 6, 3],
       [5, 5, 1, 1, 0],
       [9, 6, 6, 6, 2],
       [9, 8, 3, 2, 1]])

Example

Sort a 2-D array in ascending order along axis=0 using numpy.sort.

1print(a2) # original 2-D array
2np.sort(a2, axis=0)  # ascending order along axis=0
[[3 6 6 9 9]
 [1 5 1 0 5]
 [6 6 2 6 9]
 [8 3 2 1 9]]

array([[1, 3, 1, 0, 5],
       [3, 5, 2, 1, 9],
       [6, 6, 2, 6, 9],
       [8, 6, 6, 9, 9]])

Observe that the columns of the 2-D array are sorted in ascending order along axis=0 from smallest to largest.

Note

In the sorting of 2-D arrays, the rows or columns are sorted independently. This also applies to sorting of arrays of higher dimensions.

The numpy.ndarray.sort Method

The numpy.ndarray.sort method sorts an array in-place. The only difference between the previous numpy.sort function and the numpy.ndarray.sort method is that the latter method sorts an array in-place whereas the former function returns a copy.

Example

Sort a 1-D array in ascending order using the sort method.

1a1.sort
2print(a1)
[0 1 1 1 2 4 4 6 6 6 7 7 8 9 9]

Example

Sort a 2-D array in ascending order along axis=0 using the sort method.

1a2.sort(axis=0)
2print(a2)
[[1 3 1 0 5]
 [3 5 2 1 9]
 [6 6 2 6 9]
 [8 6 6 9 9]]

ADVERTISEMENT



The numpy.argsort Function.

The numpy.argsort function returns the indices that would sort an array. As we will see in a moment, the function can be used to sort a 2-D array by a certain column or row. This is in contrast to the numpy.sort function where the rows or columns are sorted independently.

Syntax

The numpy.argsort function.

1numpy.argsort(a, axis=- 1, kind=None, order=None)
Parameter Required? Default Value Description
a ✔️ Yes NA Array to be sorted.
axis ❌ No -1 Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis.
kind ❌ No None Sorting algorithm. The default is ‘quicksort’.
order ❌ No None When a is an array with fields defined, this argument specifies which fields to compare first, second, etc.
Note

The numpy.argsort function is equivalent to the numpy.ndarray.argsort method. The only difference is that the function takes in array a as an additional parameter.

Example

Sort a 2-D array by first column using numpy.argsort.

We first get the indices of the first column corresponding to the smallest to largest values.

1print(a2) # original 2-D array
2ind = a2[:, 0].argsort()  # indices
3print(ind)
[[3 6 6 9 9]
 [1 5 1 0 5]
 [6 6 2 6 9]
 [8 3 2 1 9]]

[1 0 2 3]

The array of indices indicates that the smallest value has an index of 1, the second smallest value has an index of 0, and so on.

To sort the array by the first column, we simply insert indices into the a2 array.

1print(a2[ind])
[[1 5 1 0 5]
 [3 6 6 9 9]
 [6 6 2 6 9]
 [8 3 2 1 9]]

We see that the rows have been sorted by the first column in ascending order.

Example

Sort a 2-D array by last row using numpy.argsort.

We first get the indices of the last row corresponding to the smallest to largest values.

1ind1 = a2[-1, :].argsort()  # indices
2print(ind1)
[3 2 1 0 4]

The array of indices indicates that the smallest value has an index of 3, the second smallest value has an index of 2, and so on.

To sort the array by the last row, we simply insert the indices into the a2 array.

1print(a2[:,ind1])
[[9 6 6 3 9]
 [0 1 5 1 5]
 [6 2 6 6 9]
 [1 2 3 8 9]]

We see that the columns have been sorted by the last row in ascending order.