TExcelTAD
Home › NumPy › NumPy Array Sort

NumPy Array Sort

Sorting puts elements into an ordered sequence: numbers ascending, strings alphabetically, booleans False before True. NumPy's np.sort() returns a sorted copy and leaves the original unchanged.

python · try it yourself
import numpy as np

race_times = np.array([12.8, 11.9, 13.4, 12.1, 11.7])
print(np.sort(race_times))
print(race_times)                       # unchanged

print(np.sort(np.array(["pear", "Apple", "fig", "banana"])))
print(np.sort(np.array([True, False, True])))
[11.7 11.9 12.1 12.8 13.4]
[12.8 11.9 13.4 12.1 11.7]
['Apple' 'banana' 'fig' 'pear']
[False  True  True]

Notice "Apple" comes first: strings sort by character code, and uppercase letters have smaller codes than lowercase ones.

Sorting in place

The method a.sort() sorts the array itself and returns None. Use it when you don't need the original order any more and want to save memory:

python · try it yourself
import numpy as np

queue = np.array([5, 2, 9, 1])
result = queue.sort()
print(queue, result)
[1 2 5 9] None

Descending order

There is no reverse=True option. Sort ascending and reverse with a [::-1] slice, or sort the negated values:

python · try it yourself
import numpy as np

points = np.array([40, 95, 63, 78])
print(np.sort(points)[::-1])
print(-np.sort(-points))
[95 78 63 40]
[95 78 63 40]

Sorting 2-D arrays

For a 2-D array, np.sort sorts along the last axis by default, which means each row is sorted on its own. Use axis=0 to sort each column, or axis=None to flatten and sort everything:

python · try it yourself
import numpy as np

m = np.array([[9, 2, 7],
              [4, 8, 1]])
print(np.sort(m))              # each row
print(np.sort(m, axis=0))      # each column
print(np.sort(m, axis=None))   # everything, flattened
[[2 7 9]
 [1 4 8]]
[[4 2 1]
 [9 8 7]]
[1 2 4 7 8 9]

Warning: Sorting each column independently breaks up the rows. If every row is a record (a person, a product), that scrambles your data. To sort records by one column, use argsort, below.

argsort: the order, not the values

np.argsort(a) returns the indices that would sort the array. Those indices can then reorder this array or any parallel array, which is how you sort records by a key:

python · try it yourself
import numpy as np

names = np.array(["Ana", "Ben", "Chen", "Dara"])
ages = np.array([34, 25, 41, 29])

order = np.argsort(ages)
print(order)
print(names[order])            # names sorted by age
print(ages[order])

# Rows of a table sorted by the 2nd column
table = np.array([[1, 300], [2, 100], [3, 200]])
print(table[table[:, 1].argsort()])
[1 3 0 2]
['Ben' 'Dara' 'Ana' 'Chen']
[25 29 34 41]
[[  2 100]
 [  3 200]
 [  1 300]]

Sorting by several keys: np.lexsort

np.lexsort sorts by multiple keys. The last key you pass is the primary one:

python · try it yourself
import numpy as np

teams = np.array(["red", "blue", "red", "blue", "red"])
scores = np.array([7, 9, 5, 9, 7])
players = np.array(["Ivy", "Max", "Lou", "Ada", "Sam"])

# primary: team, then score, then name
order = np.lexsort((players, scores, teams))
for i in order:
    print(teams[i], scores[i], players[i])
blue 9 Ada
blue 9 Max
red 5 Lou
red 7 Ivy
red 7 Sam

Partial sorting: top-k

If you only need the k smallest values, np.partition(a, k) is faster than a full sort: it guarantees that the element at position k is in its sorted place, with smaller ones before it (in any order) and larger ones after.

python · try it yourself
import numpy as np

latencies = np.array([88, 12, 47, 5, 63, 21, 99, 34])
print(np.sort(np.partition(latencies, 3)[:3]))   # three fastest
[ 5 12 21]

Test yourself

What does a.sort() return?

  1. A sorted copy
  2. None (it sorts a in place)
  3. The sorting indices
  4. A boolean

What is np.argsort(np.array([30, 10, 20]))?

  1. [10 20 30]
  2. [1 2 0]
  3. [2 0 1]
  4. [0 1 2]

By default, how does np.sort treat a 2-D array?

  1. Sorts each row
  2. Sorts each column
  3. Flattens then sorts
  4. Sorts rows by their first value