A universal function (ufunc) applies a mathematical operation element-wise across an entire array, in compiled C. NumPy ships fast versions of all the common maths functions.
Common ufuncs
a = np.array([1, 4, 9, 16])np.sqrt(a) # [1. 2. 3. 4.]np.log(a) # natural log of eachnp.exp(a) # e**eachnp.round(a * 1.5, 2)np.abs(a - 10)np.maximum(a, 5) # element-wise max against 5
Why not math.sqrt?
Binary ufuncs
Some ufuncs take two arrays and combine them element-wise — np.add, np.maximum, np.power — and they broadcast (next chapter):
np.add(a, b) # same as a + bnp.power(a, 2) # same as a ** 2np.minimum(a, b) # element-wise minimum
Key takeaways
- 01ufuncs apply element-wise math across a whole array in compiled C.
- 02Common ones: sqrt, log, exp, round, abs, sin/cos.
- 03Use np.sqrt (not math.sqrt) on arrays — math functions only take scalars.
- 04Binary ufuncs (add, maximum, power) combine two arrays element-wise and broadcast.
