Sort, rank, and search arrays

2.5.5

Use positions for indirect sorting, find matching locations, and search a sorted array.

On this page

Preserve alignment with argsort

np.sort returns sorted values. np.argsort returns positions, which you can reuse to sort related arrays together. Set stable=True when tied values should keep their original order.

import numpy as np

names = np.array(["Tea", "Cake", "Coffee"])
counts = np.array([4, 1, 3])
order = np.argsort(counts, stable=True)
print(names[order].tolist())
Example output
['Cake', 'Coffee', 'Tea']

Find positions and insertion points

flatnonzero gives positions of true entries in a flattened mask. searchsorted gives insertion positions for sorted arrays. side="left" finds the first valid position before equal values.

import numpy as np

scores = np.array([10, 20, 20, 50])
print(np.flatnonzero(scores >= 20).tolist())
print(np.searchsorted(scores, 20, side="left"))
Example output
[1, 2, 3]
1

Official references