This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 6: NumPy functions

Sorting arrays

face Josiah Wang

You can sort an array using np.sort().

>>> x = np.array([3, 1, 2])
>>> sorted_x = np.sort(x)
>>> print(sorted_x)
[1 2 3]

The OOP version x.sort() is a mutator method that sorts x in-place, rather than returning a copy like np.sort(x).

You can also sort across rows or columns by specifying the axis.

>>> y = np.array([[6, 4], [1, 0], [2, 7]])
>>> print(y)
[[6 4]
 [1 0]
 [2 7]]
>>> print(np.sort(y, axis=0))  # Sort rows
[[1 0]
 [2 4]
 [6 7]]
>>> print(np.sort(y, axis=1)) # Sort columns
[[4 6]
 [0 1]
 [2 7]]

To get the indices after a sort, use np.argsort(x) (or x.argsort()).

>>> x = np.array([3, 1, 2])
>>> print(np.argsort(x))
[1 2 0]
>>> y = np.array([[6, 4], [1, 0], [2, 7]])
>>> print(np.argsort(y, axis=0)) # Get indices of rows after sorting 
[[1 1]
 [2 0]
 [0 2]]
>>> print(np.argsort(b, axis=1)) # Get indices of columns after sorting
[[1 0]
 [1 0]
 [0 1]]