Skip to content
ml-recall

Topic notes

NumPy

Practical NumPy — array creation, indexing (views vs copies), broadcasting, reductions and axes, reshape order, dtype casting and promotion, and the classic gotchas.

4-min read AI-checked

Practise 116 questions Take a test

Key ideas

Formulas

Worked example

a has shape (4, 1, 3) and b shape (5, 1). Pad b on the left to (1, 5, 1) and compare position by position: 44 vs 11 → 4, 11 vs 55 → 5, 33 vs 11 → 3, so a + b is (4, 5, 3). Adding a (5,) array to a instead fails, because 5 meets the trailing 3; (3,), (5, 3) and (4, 1) all work, the last giving (4, 4, 3).

Row-normalising X = [[0, 1, 2], [3, 4, 5]]: X.sum(axis=1) is [3, 12] with shape (2,), which lines up with the 3 columns and raises; X / X.sum(axis=1, keepdims=True) divides each row by its own sum, and the rows then sum to 1.

In code

import numpy as np
a = np.arange(6)
a[::2][0] = 9; a[[1, 3]][0] = 9            # slice = view (write sticks); fancy index = copy (lost)
print(a)                                   # [9 1 2 3 4 5]
x, y = np.zeros(3), np.zeros(3)
x[[0, 0, 2]] += 1; np.add.at(y, [0, 0, 2], 1)
print(x, y)                                # [1. 0. 1.] [2. 0. 1.]
u = np.array([250, 5], dtype=np.uint8) + 10
print(u, u.dtype)                          # [ 4 15] uint8
i = np.array([1, 2, 3])
try: i += 0.5
except TypeError as e: print(type(e).__name__)   # UFuncTypeError
print(np.std([1, 2, 3, 4]).round(3), np.std([1, 2, 3, 4], ddof=1).round(3))   # 1.118 1.291
print(np.arange(1, 1.3, 0.1))              # [1.  1.1 1.2 1.3]: stop included by rounding

Common pitfalls

References

  1. NumPy documentation: Broadcasting — General broadcasting rules
  2. NumPy documentation: Indexing on ndarrays — Basic indexing; Advanced indexing (Integer array indexing, Boolean array indexing); Assigning values to indexed arrays
  3. NumPy documentation: Copies and views — View; Copy; Other operations; How to tell if the array is a view or a copy
  4. NumPy documentation: numpy.arange — Parameters (stop); Returns; Warning
  5. NumPy documentation: Universal functions (ufunc) — Optional keyword arguments (out, casting); Methods (ufunc.at)
  6. NumPy documentation: Data type promotion in NumPy — Detailed behavior of Python scalars
  7. NumPy documentation: numpy.std — Parameters (ddof, keepdims); Notes
  8. NumPy documentation: numpy.argmax — Parameters (axis); Examples (np.unravel_index)