With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

Creating a universal function

We can create a universal function from a Python function with the frompyfunc() NumPy function.

How to do it...

The following steps help us create a universal function:

1. Define a simple Python function that doubles the input:
def double(a):
return 2 * a
2. Create the universal function with frompyfunc(). Specify the number of input arguments and the number of objects (both are equal to 1) 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]

How it works...

We defined a Python function that doubles the numbers it receives. Actually, we can also have ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

No credit card required