NumPy Ufuncs
- Previous Page NumPy Random
- Next Page Introduction
What are ufuncs?
Ufuncs refer to 'Universal Functions', which are NumPy functions that operate on ndarray objects.
Why use ufuncs?
ufunc is used to implement vectorization in NumPy, which is much faster than iterating over elements.
They also provide broadcasting and other methods, such as reduction, accumulation, etc., which are very helpful for computation.
Ufuncs also accept other parameters, such as:
where
Boolean array or condition, used to define where the operation should be performed.
dtype
Define the return type of the element.
out
The return value should be copied to the output array.
What is vectorization?
Converting iterative statements to vector-based operations is called vectorization.
Since modern CPUs have been optimized for such operations, they are faster.
Add the elements of the two lists:
List 1: [1, 2, 3, 4]
List 2: [4, 5, 6, 7]
One way is to iterate through two lists and sum each element.
Example
If there is no ufunc, we can use Python's built-in zip()
Method:
x = [1, 2, 3, 4] y = [4, 5, 6, 7] z = [] for i, j in zip(x, y): z.append(i + j) print(z)
For this, NumPy has a ufunc called add(x, y)
It will output the same result.
Example
We can use ufunc to do this add()
Function:
import numpy as np x = [1, 2, 3, 4] y = [4, 5, 6, 7] z = np.add(x, y) print(z)
- Previous Page NumPy Random
- Next Page Introduction