LA ILAHA ILLA HU
Allah, Your Lord There Is No Deity Except Him.
Python Data Science NumPy ufuncs Introduction
"Universal Functions" Or ufuncs are "Universal Functions" and they are very much NumPy functions that operates on the ndarray object.
Why are ufuncs used?
ufuncs are used to implement vectorization in NumPy which is way faster than iterating over
elements. ufuncs also provide broadcasting and additional methods like reduce, accumulate etc.
which are very helpful for computation.
ufuncs also take additional arguments, like:
1. where ( boolean array or condition defining where the operations should take place ).
2. dtype ( defining the return type of elements ).
3. out (output array where the return value should be copied).
What is Vectorization?
Vectorization is converting iterative statements into a vector based operation.
It is faster as modern CPUs are optimized for such operations.
The add() function in NumPy
Suppose we were to add the Elements of Two Lists.
list 1: [11, 12, 13, 14]
list 2: [14, 15, 16, 17]
Example 1: list 1: [11, 12, 13, 14], list 2: [14, 15, 16, 17].
Without ufunc: One way of doing it is to iterate over both of the lists and then sum each elements.
Code
x = [11, 12, 13, 14]
y = [14, 15, 16, 17]
z = []
for i, j in zip(x, y): z.append(i + j) print(z)
the output will be
[25, 27, 29, 31]
NumPy offers ufunc for this, called add(x, y) that will produce the same result.
Example 2 Without ufunc:: list 1: [11, 12, 13, 14], list 2: [14, 15, 16, 17]. With ufunc, we can use the add() function.
Code
import numpy as np
x = [11, 12, 13, 14]
y = [14, 15, 16, 17]
z = np.add(x, y)
print(z)
the output will be
[25, 27, 29, 31]
Note: NumPy ufunc Universal function or ufuncs is a function which operates on ndarrays in an element by element fashion and supports array broadcasting, type casting, and many other standard features.