import numpy as np
# Define a custom Python function
def custom_func(x):
return x ** 2 + 2 * x + 1
# Create a ufunc from the custom function
custom_ufunc = np.frompyfunc(custom_func, 1, 1)
# Test the ufunc with a NumPy array
arr = np.array([1, 2, 3, 4, 5])
result = custom_ufunc(arr)
print(result) # Output: [ 4 9 16 25 36]
import numpy as np
# Define a custom Python function
def custom_func(x):
return x ** 2 + 2 * x + 1
# Create a vectorized function from the custom function
custom_ufunc = np.vectorize(custom_func)
# Test the vectorized function with a NumPy array
arr = np.array([1, 2, 3, 4, 5])
result = custom_ufunc(arr)
print(result) # Output: [ 4 9 16 25 36]
Both methods allow you to create custom ufuncs from Python functions. Using custom ufuncs can be useful for extending NumPy's functionality with custom operations tailored to your specific needs.