We use np.frompyfunc() to turn a normal Python function into a fast, element-wise function that works on arrays.
np.frompyfunc() for ufunc creation in NumPy
np.frompyfunc(func, nin, nout)
func is the Python function you want to convert.
nin is the number of input arguments your function takes.
nout is the number of outputs your function returns.
def add_one(x): return x + 1 ufunc_add_one = np.frompyfunc(add_one, 1, 1)
def sum_and_diff(x, y): return x + y, x - y ufunc_sum_diff = np.frompyfunc(sum_and_diff, 2, 2)
This code defines a simple function that doubles the first input and adds the second. Then it creates a ufunc from it. Finally, it applies this ufunc to two arrays element-wise and prints the result.
import numpy as np def multiply_and_add(x, y): return x * 2 + y # Create ufunc from the Python function ufunc = np.frompyfunc(multiply_and_add, 2, 1) # Sample arrays arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) # Apply ufunc element-wise result = ufunc(arr1, arr2) print(result)
The output of np.frompyfunc() is always an object array, so results may need conversion if you want numeric types.
Using np.frompyfunc() is slower than built-in ufuncs but faster than looping manually in Python.
np.frompyfunc() converts a Python function into a NumPy ufunc for element-wise operations.
It requires specifying how many inputs and outputs the function has.
The created ufunc works on arrays just like built-in NumPy functions.