Sorting and Searching
Python · NumPy Library
Theory
np.sort(arr) returns a sorted copy in ascending order, and arr.sort() sorts in place; for descending order reverse it with [::-1]. np.argsort(arr) returns the positions that would sort the array, which lets you reorder a second array the same way, for example names[np.argsort(-scores)] gives names from highest to lowest score.
np.where(cond) returns the positions where a condition is True, and np.where(cond, a, b) builds a new array taking a where True and b where False, like a vectorised if-else. np.unique(arr, return_counts=True) gives the distinct values in sorted order with how often each appears. np.searchsorted(sorted_arr, value) finds where a value would be inserted to keep the order, which is handy for putting amounts into slabs or bins.
Why we use it
Ranking, finding the top items, counting categories and labelling values are everyday tasks. These functions do them on whole arrays without loops, and argsort keeps related arrays aligned when you reorder.
When to use it
Use argsort to rank or to sort several arrays together, np.where for if-else labels, unique with counts for frequency tables and searchsorted for bucketing into sorted thresholds. For labelled data, pandas sort_values and value_counts read better.
How it works
- Array to organise
- Need the values in order? Yes: np.sort (copy) or arr.sort() (in place). No: Keep going.
- Need to reorder another array the same way? Yes: order = np.argsort(a); other[order]. No: Keep going.
- Need an if-else label per value? Yes: np.where(cond, a, b). No: Keep going.
- Count categories with np.unique(a, return_counts=True)
- Sorted, ranked, labelled or counted result
Syntax
np.sort(a) a.sort() np.sort(a)[::-1]
np.argsort(a)
np.where(cond) np.where(cond, x, y)
np.unique(a, return_counts=True)
np.searchsorted(sorted_a, v)Example
scores = np.array([72, 95, 64])
print(np.argsort(scores)) # [2 0 1]
print(np.where(scores >= 70, 'Pass', 'Fail'))Key points
- np.sort returns a copy; arr.sort() changes arr itself
- argsort gives positions; use them to reorder other arrays
- Sort descending with np.sort(a)[::-1] or argsort(-a)
- np.where(cond) gives positions; np.where(cond, a, b) gives values
- searchsorted needs its first argument already sorted