Skip to content

Lesson 5 of 9 · 25m

Vectorization with NumPy: Move the Loop Out of Python

NumPy's speed comes from contiguous typed memory and loops implemented in C. Learn the layouts, dtype choices, and pandas traps that decide whether vectorization works.

NumPy is not fast because arrays are magical. It is fast because a million numbers become a contiguous block of fixed-width values, and the loop over them runs in compiled C without a Python object allocation per element. Once you understand that, most NumPy performance advice becomes obvious: keep data numeric, dense, and vector-shaped for as long as possible.

Replace elementwise Python with array expressions

A pure-Python loop performs one bytecode-rich multiply/add sequence per row. The vectorized version moves that loop into NumPy:

import numpy as np

prices = np.array([19.99, 4.50, 7.25], dtype=np.float64)
quantities = np.array([3, 12, 8], dtype=np.int32)
total = float((prices * quantities).sum())

At three rows this is absurd ceremony. At three million rows it is the difference between seconds and milliseconds. Vectorization pays when the loop trip count is large and the per-element operation is simple enough that interpreter overhead dominates.

dtype and shape are performance decisions

a = np.arange(1_000_000, dtype=np.int64)   # about 8 MB
b = np.arange(1_000_000, dtype=np.int32)   # about 4 MB

Smaller dtypes reduce memory bandwidth pressure and cache misses. But do not guess: integer overflow, floating precision, and interoperability constraints come first. Similarly, a contiguous C-order array is usually easier for NumPy to process than a strided view; transposing data does not copy, but downstream operations may become slower because memory access is no longer linear.

Check what you actually have:

print(a.dtype, a.shape, a.strides, a.flags["C_CONTIGUOUS"])

Avoid object arrays and Python callbacks

The two silent performance killers are dtype=object and np.vectorize used as a cosmetic wrapper. An object array is an array of pointers to Python objects — much of the numeric advantage is gone — and np.vectorize still calls Python per element. Use true ufuncs and broadcasting:

x = np.linspace(0.0, 1.0, 1_000_000)
y = np.exp(-x) * np.sqrt(x + 1.0)

If the expression allocates several large temporaries, numexpr can fuse operations and reduce memory traffic. Measure it; do not adopt it as decoration.

pandas: vectorize columns, not rows

In pandas, prefer column operations and query the dtypes:

df["revenue"] = df["unit_price"] * df["quantity"]
df["discounted"] = np.where(df["quantity"] >= 10, df["revenue"] * 0.9, df["revenue"])

df.apply(..., axis=1) often means "run Python once per row." Sometimes that is fine for clarity or irregular logic. In hot code it is usually the line your profiler is trying to show you. Rewrite with vectorized methods, categoricals, NumPy extraction via .to_numpy(), or a different table shape.

Field notes

  • Vectorization helps arithmetic; it does not fix a bad algorithm or unnecessary I/O.
  • Copies hide in innocent expressions. Inspect .shape conversions, .copy() calls, and pandas indexing behavior.
  • Parallel NumPy builds can oversubscribe CPU when BLAS threads multiply across processes. Set thread counts deliberately.
  • Validate numerical correctness after dtype optimization. float32 speed is not worth silently wrong totals.

Was this lesson helpful?

Sign in to rate