Skip to main content
Albero Academy

Sorting & Searching

Sort arrays, get the sort order with argsort, and count uniques.

Manipulation9 min

Organising and summarising values — sorting them, finding where a value belongs, counting occurrences — comes up in almost every analysis. NumPy does it all 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] — a sorted copy
np.sort(m, axis=1) # sort within each row

argsort — sort one array by another

argsort returns the indices that would sort the array — the key to "sort records by a column":

argsort
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']

Unique & counting

frequency table
cats = np.array(["a", "b", "a", "c", "a"])
vals, counts = np.unique(cats, return_counts=True)
# vals = ['a' 'b' 'c'], counts = [3 1 1]

Key takeaways

  1. 01np.sort returns a sorted copy; pass axis to sort within rows/columns.
  2. 02argsort returns the indices that would sort — use it to reorder another array.
  3. 03np.unique(return_counts=True) builds a frequency table.
  4. 04The arg-variants return positions you can index with.

Finished this chapter?

Mark it complete to track your progress through NumPy.