Page4/12
Universal Functions (ufuncs) · Page 1 of 1
Vectorizing Math Operations
Universal Functions (ufuncs)
What is a ufunc?
A ufunc (universal function) is a function that operates on ndarrays element-by-element. They are written in C and are the reason NumPy is fast.
Why ufuncs over Loops?
A Python for loop has to check types and dispatch functions on every single iteration. A ufunc pushes the loop down to C, bypassing Python overhead entirely.
Common ufuncs
| Math | Trigonometric | Comparison |
|---|---|---|
np.add | np.sin | np.greater |
np.subtract | np.cos | np.less |
np.multiply | np.exp | np.equal |
np.sqrt | np.log | np.isnan |
Aggregations
ufuncs have methods to collapse arrays:
arr = np.array([1, 2, 3, 4])
arr.sum()
arr.mean()
arr.cumsum() # Cumulative sum: [1, 3, 6, 10]
main.py
Loading...
OUTPUT
▶Click "Run Code" to execute…