Skip to main content
Albero Academy

Sorting, Searching & Counting

Sort arrays and get the sorting order, find insertion points, and count unique values — the toolkit for organising data.

Chapter 7NumPy14 min readBeginner friendly
  • #NumPy
  • #Sorting
  • #Searching

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

sort values
a = np.array([3, 1, 4, 1, 5])
np.sort(a) # [1 1 3 4 5] returns a sorted copy
a.sort() # sorts a in place
m = 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":

sort one array by another
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)

searchsorted finds where values would slot into a sorted array to keep it ordered — a vectorised binary search, ideal for bucketing:

binary search & bucketing
grades = np.array([40, 60, 75, 90]) # boundary marks, ascending
np.searchsorted(grades, [55, 82]) # [1 3] → which band each score falls in
np.argmax(a) # index of the max
np.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:

frequencies
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

  1. 01np.sort returns a sorted copy; .sort() sorts in place; both take an axis.
  2. 02argsort returns the indices that would sort — use it to sort one array by another.
  3. 03searchsorted is a vectorised binary search into a sorted array — great for bucketing.
  4. 04np.unique(return_counts=True) builds a frequency table; np.bincount counts non-negative ints.
  5. 05The arg-variants (argsort, argmax, nonzero) return positions, which you then index with.