3.1 Universal Functions
: 20 minutes
Now that we know how to create new tensors or NumPy arrays, let us talk about some of the vectorized operations we can perform on them. NumPy offers many built-in universal functions, also knowns as ufunc, for element-wise vectorized operations.
The universal functions can be placed into two categories: uniary and binary. Unary functions take an array and returns the output array, while binary functions take two input arrays to perform binary operations on them.
Unary Functions
Some of the most commonly used unary ufuncs are listed in the table below.
Ufunc | Description |
---|---|
sqrt |
Compute the element-wise square root (equivalent to arr ** 0.5 ) |
square |
Compute the square of each element (equivalent to arr ** 2 ) |
exp |
Compute the exponent e^x of each element |
sign |
Compute the sign of each element: 1 (positive), 0 (zero), or –1 (negative) |
ceil |
Compute the ceiling of each element (i.e., the smallest integer greater than or equal to that number) |
floor |
Compute the floor of each element (i.e., the largest integer less than or equal to each element) |
abs , fabs |
Compute the absolute value element-wise for integer, floating-point, or complex values |
isnan |
Return Boolean array indicating whether each value is NaN (Not a Number) |
isfinite , isinf |
Return Boolean array indicating whether each element is finite (non-inf , non-NaN ) or infinite, respectively |
log , log10 , log2 , log1p |
Natural logarithm (base e), log base 10, log base 2, and log(1 + x), respectively |
rint |
Round elements to the nearest integer, preserving the dtype |
cos , cosh , sin , sinh , tan , tanh |
Regular and hyperbolic trigonometric functions |
arccos , arccosh , arcsin , arcsinh , arctan , arctanh |
Inverse trigonometric functions |
The following example uses numpy.square
to perform element-wise squaring of an array arr
.
Binary Functions
Some of the most commonly used binary ufuncs are listed in the table below.
Ufunc | Description |
---|---|
add |
Add corresponding elements in arrays |
subtract |
Subtract elements in second array from first array |
multiply |
Multiply array elements |
divide , floor_divide |
Divide or floor divide (truncating the remainder) |
power |
Raise elements in first array to powers indicated in second array |
maximum |
Element-wise maximum; fmax ignores NaN |
minimum |
Element-wise minimum; fmin ignores NaN |
mod |
Element-wise modulus (remainder of division) |
The following example uses numpy.maximum
to select (element-wise) maximum from two arrays.
We can also use numpy.add
to (element-wise) add two arrays. Here, the elements of matrix A
and B
are distributed normally with different means and standard deviations.