Vectorization — operating on entire arrays at once instead of element-by-element in a Python loop — is the reason NumPy is fast and expressive. Paired with broadcasting, which lets arrays of different shapes combine, it's how you write real numerical code.
Vectorization
Arithmetic operators work element-wise across a whole array — no loop needed:
prices = np.array([100, 250, 90, 400])prices * 1.18 # add 18% GST to every priceprices - prices.mean() # centre each valueprices > 150 # element-wise comparisona = np.array([1, 2, 3])b = np.array([10, 20, 30])a + b # [11 22 33] element-wisea * b # [10 40 90]
Universal functions (ufuncs)
NumPy ships fast, element-wise versions of the maths functions, applied to the whole array at once:
np.sqrt(prices)np.log(prices)np.round(prices * 1.18, 2)np.abs(a - b)np.exp(a)np.maximum(a, b) # element-wise max of two arrays
Broadcasting
Broadcasting is the rule that lets NumPy combine arrays of different shapes by virtually stretching the smaller one. A scalar broadcasts to every element; a row vector broadcasts down every row:
m = np.array([[1, 2, 3],[4, 5, 6]]) # shape (2, 3)m + 10 # scalar → added to every elementcol_means = m.mean(axis=0) # shape (3,) → [2.5 3.5 4.5]m - col_means # subtract each column's mean (broadcast down)
np.where — vectorised if/else
np.where(condition, a, b) picks from a where the condition is true and b where it's false — element-wise, no loop:
scores = np.array([55, 82, 47, 91])labels = np.where(scores >= 60, "pass", "fail")# array(['fail', 'pass', 'fail', 'pass'])# Cap values at 100capped = np.where(scores > 100, 100, scores)
Practice
Given an array of raw exam scores, write one line to standardise them (subtract the mean, divide by the standard deviation) using broadcasting. Then use np.where to label each as "distinction" (≥75), "pass" (≥40) or "fail".
Key takeaways
- 01Vectorization applies operators across whole arrays at once — faster and cleaner than loops.
- 02ufuncs (np.sqrt, np.log, np.round…) are fast element-wise maths functions.
- 03Broadcasting stretches smaller shapes to fit larger ones — the basis of normalising data.
- 04Broadcasting rule: shapes are compatible from the right when equal or one is 1.
- 05np.where(cond, a, b) is a vectorised if/else for element-wise selection.
