Ufuncs apply a function element-wise on arrays, implemented in compiled code. They are the engine behind NumPy vectorization.
Built-in ufuncs
- Arithmetic:
np.add,np.multiply,np.power - Math:
np.sin,np.log,np.exp - Comparison:
np.greater,np.equal - Reductions:
np.add.reducesums along an axis
Operators map to ufuncs
import numpy as np
a = np.array([1, 4, 9])
print(np.sqrt(a))
print(np.equal(a, 4))
Output dtype
Ufuncs respect dtype promotion rules. Integer division may need astype(float) first for fractional results.
Important interview questions and answers
- Q: Why ufuncs vs Python loop?
A: Loop in Python; ufunc dispatches to SIMD/C loops on contiguous memory. - Q: np.add.reduce?
A: Equivalent to sum for 1D—generalizes to higher dimensions with axis.
Self-check
- Apply log to a positive float array.
- Which ufunc checks element equality?
Tip: Replace Python loops with ufuncs—profile if still slow.
Interview prep
- What is ufunc?
Universal function—element-wise compiled operation on arrays.
- Why not loop?
Python per-element overhead; ufuncs batch in C/SIMD.