Organising and summarising values — sorting them, finding where a value belongs, counting how often each appears — comes up in nearly every analysis. NumPy does all of it vectorised, and the arg* variants return positions, which is what makes them powerful.
Sorting
a = np.array([3, 1, 4, 1, 5])np.sort(a) # [1 1 3 4 5] returns a sorted copya.sort() # sorts a in placem = np.array([[3, 1], [2, 4]])np.sort(m, axis=1) # sort within each row → [[1 3] [2 4]]
argsort & sorting by a key
argsort returns the indices that would sort the array. That's how you sort one array by another — the essence of "sort records by a column":
names = np.array(["Ana", "Ravi", "Kai"])scores = np.array([82, 95, 68])order = np.argsort(scores)[::-1] # descending → [1 0 2]names[order] # ['Ravi' 'Ana' 'Kai'] (top scorer first)
Searching
searchsorted finds where values would slot into a sorted array to keep it ordered — a vectorised binary search, ideal for bucketing:
grades = np.array([40, 60, 75, 90]) # boundary marks, ascendingnp.searchsorted(grades, [55, 82]) # [1 3] → which band each score falls innp.argmax(a) # index of the maxnp.nonzero(a > 3) # indices where the condition holds
Unique & counting
Find distinct values and how often each occurs — the NumPy equivalent of a frequency table:
cats = np.array(["a", "b", "a", "c", "b", "a"])vals, counts = np.unique(cats, return_counts=True)# vals = ['a' 'b' 'c']# counts = [3 2 1]np.bincount([0, 1, 1, 3]) # [1 2 0 1] counts of each non-neg int
Practice
Sort a table of students by score descending using argsort and reorder their names to match. Use searchsorted to assign letter-grade bands to a list of marks. Build a frequency table of a categorical array with np.unique(..., return_counts=True).
Key takeaways
- 01np.sort returns a sorted copy; .sort() sorts in place; both take an axis.
- 02argsort returns the indices that would sort — use it to sort one array by another.
- 03searchsorted is a vectorised binary search into a sorted array — great for bucketing.
- 04np.unique(return_counts=True) builds a frequency table; np.bincount counts non-negative ints.
- 05The arg-variants (argsort, argmax, nonzero) return positions, which you then index with.
