sort() and argsort() (NumPy)

np.sort() returns a sorted copy of an array, and np.argsort() returns the indices that would sort it. Sorting works along an axis, and argsort is the key to ordering one array by the values of another.

NumPy

np.sort(a) gives the values in ascending order without changing the original, while the method a.sort() sorts in place. On a 2-D array the axis argument decides whether each row or each column is sorted independently; the default sorts along the last axis.

argsort returns positions instead of values: the indices that, if you applied them, would put the array in order. This is what lets you sort parallel arrays together — sort one column and reorder the others by the same index — and it underlies things like ranking and top-k selection.

For descending order, sort ascending and reverse with [::-1], or negate the array before argsort. The kind argument selects the algorithm (quicksort, mergesort for stability, heapsort).

Syntax

np.sort(a, axis=-1)  |  np.argsort(a)

Examples

Python — Indices that would sort a into [1, 2, 3].

import numpy as np
a = np.array([3, 1, 2])
print(np.argsort(a))

Output:

[1 2 0]

Learn it in a lesson

See also

Back to the Dictionary