Universal Functions
Universal functions (ufuncs) are NumPy’s vectorised math — np.sin, np.exp, np.maximum. They run element-wise in C, broadcast automatically, and accept an out= parameter for in-place writes.
Math, comparison, reduction, accumulation
EXAMPLE
import numpy as np a = np.array([0.0, 0.5, 1.0, 1.5, 2.0]) b = np.array([1.0, 1.0, 1.0, 1.0, 1.0]) # 1) Element-wise math — all run in C, no Python loop np.sqrt(a) np.exp(a) np.log(np.where(a > 0, a, 1)) # avoid log(0) np.sin(a) ** 2 + np.cos(a) ** 2 # ≈ 1 # 2) Element-wise comparison + selection np.maximum(a, b) # element-wise max np.where(a > 1, a, 0) # ternary: a if a>1 else 0 np.clip(a, 0.5, 1.5) # squeeze to a range # 3) Broadcasting works on every ufunc m = np.arange(6).reshape(2, 3) m + np.array([10, 20, 30]) # (2,3) + (3,) → (2,3) # 4) Reductions — collapse an axis a.sum() a.mean() a.std() a.max() a.argmax() a.argmin() m.sum(axis=0) # column sums m.mean(axis=1) # row means # 5) Accumulations — cumulative versions np.cumsum([1, 2, 3]) # [1, 3, 6] np.cumprod([1, 2, 3]) # [1, 2, 6] # 6) Custom vectorisation — np.vectorize wraps a Python fn (still loop, but cleaner) f = np.vectorize(lambda x: 'big' if x > 1 else 'small') print(f(a)) # 7) The 'out=' trick — write in place, no extra allocation result = np.empty_like(a) np.multiply(a, 100, out=result)
Why it matters
When you can phrase a transformation as a ufunc, you almost always can. Replacing a Python loop with a ufunc + broadcast typically cuts runtime by 50–500x.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
import numpy as np x = np.array([1.0, 4.0, 9.0]) print(np.sqrt(x)) print(np.exp(x)) print(np.log(x))Try it Yourself »
Discussion
Loading…