NumPy ufuncs
- Previous Page NumPy Willekeurig
- Next Page Introduction
Wat zijn ufuncs?
Ufuncs verwijzen naar ' Universele Functies' (Universal Functions), dit zijn functies van NumPy die op ndarray-objecten werken.
Waarom ufunc gebruiken?
Ufunc wordt gebruikt om vectorisatie in NumPy te implementeren, wat veel sneller is dan iteratie over elementen.
They also provide broadcasting and other methods such as reduction, accumulation, etc., which are very helpful for calculations.
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 elements of two lists:
List 1: [1, 2, 3, 4]
List 2: [4, 5, 6, 7]
One method is to traverse two lists and then 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 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 Willekeurig
- Next Page Introduction