We can create a universal function from a Python function with the frompyfunc()
NumPy function.
The following steps help us create a universal function:
Define a simple Python function that doubles the input:
def double(a): return 2 * a
Create the universal function with
frompyfunc()
. Specify the number of input arguments and the number of objects (both are equal to1
) returned:from __future__ import print_function import numpy as np def double(a): return 2 * a ufunc = np.frompyfunc(double, 1, 1) print("Result", ufunc(np.arange(4)))
The code prints the following output when executed:
Result [0 2 4 6]
We defined a Python function that doubles the numbers it receives. Actually, we can also have strings as the input, as that is legal in Python. We created a universal function from this Python function with the frompyfunc()
NumPy function. A universal function is a NumPy class with special features such as broadcasting and element...