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
a = np.array([3, 1, 4, 1, 5])np.sort(a) # [1 1 3 4 5] — a sorted copynp.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":
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
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
- 01np.sort returns a sorted copy; pass axis to sort within rows/columns.
- 02argsort returns the indices that would sort — use it to reorder another array.
- 03np.unique(return_counts=True) builds a frequency table.
- 04The arg-variants return positions you can index with.
