Universal functions (ufuncs)
ufuncs are NumPy's fast built-in functions that work on every element of an array at once.
In this page:
Syntax
np.sqrt(arr)
np.exp(arr)
np.add(arr1, arr2)
np.sin(arr)
Universal functions (ufuncs)
A universal function is a vectorized function applied element by element, such as np.sqrt, np.exp, np.sin, np.add and np.maximum. They support broadcasting and optional arguments like out and where.
Binary ufuncs also offer methods such as reduce and accumulate.
Note:
np.add.reduce(a) equals a.sum(), and np.add.accumulate(a) gives running totals.
Example: Universal functions (ufuncs)
import numpy as np
a = np.array([1, 4, 9, 16])
print(np.sqrt(a))
print(np.exp(np.array([0, 1])))
print(np.maximum(a, 5))
print(np.add.accumulate(a))
# Output:
# [1. 2. 3. 4.]
# [1. 2.71828183]
# [ 5 5 9 16]
# [ 1 5 14 30]
Related Topics
Common Mistakes
- Using math.sqrt on arrays, which only accepts scalars
- Writing a loop where a ufunc exists
- Forgetting ufuncs return new arrays
Chapter Summary
- ufuncs operate element-wise
- They support broadcasting
- Prefer np.sqrt over math.sqrt for arrays
- reduce and accumulate aggregate
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: