Mathematical Operations
Python · NumPy Library
Theory
NumPy's universal functions (ufuncs) apply a maths function to every element and return a new array. Common ones are np.sqrt, np.exp, np.log (natural log), np.log10, np.abs, np.round(arr, 2), np.floor and np.ceil. Two-array ufuncs work position by position: np.maximum(a, b) keeps the larger value at each position and np.power(a, 2) squares.
np.clip(arr, low, high) caps values into a range, so np.clip(marks, 0, 100) turns 110 into 100. Ufuncs follow maths rules: np.sqrt of a negative number gives nan and np.log(0) gives -inf, each with a RuntimeWarning rather than an error. Because they run in compiled code they are much faster than calling math.sqrt in a loop, and they also accept pandas Series and return results with the same index.
Why we use it
Data work needs transformations like log for skewed amounts, square roots for distances, rounding for display and clipping to remove impossible values. Ufuncs do these for a whole array in one call, quickly and readably.
When to use it
Use ufuncs instead of Python's math module whenever the input is an array. Use np.log1p for data that contains zeros, np.clip to cap outliers, and np.round only for display, not before further calculations.
How it works
- Numeric array
- Pick a ufunc: np.sqrt, np.log, np.round, np.clip ...
- Can any value be outside the function's domain (negative, zero)? Yes: Clean or use np.log1p first. No: Apply directly.
- Compiled loop computes the function for every element
- New array with the same shape
Syntax
np.sqrt(a) np.exp(a) np.log(a) np.log10(a)
np.abs(a) np.round(a, 2) np.floor(a) np.ceil(a)
np.clip(a, low, high) np.maximum(a, b)Example
x = np.array([16.0, 49.0, 110.0])
print(np.sqrt(x))
print(np.clip(x, 0, 100))Key points
- Ufuncs apply element-wise and return a new array
- np.log is the natural log; use np.log10 for base 10
- np.maximum compares two arrays; np.max finds one largest value
- Invalid inputs give nan or inf with a warning, not an error
- np.clip(a, low, high) caps values into a range