I made a simple function in python and I would like to use it now with numpy arrays. The function has an argument with a default value that can therefore normally be omitted. However, when using frompyfunc, omitting the default argument will not work. Why? And how can the original function be used then with numpy.arrays?
import numpy as np.array
# define a simple f with 2 args, one of them defaults to 1
def my_func(x, y=1):
return x + y
# create ufunc to work with arrays
# refer to original my_func, declare 2 inputs (x and y), 1 output (x + y)
my_ufunc = np.frompyfunc(my_func, 2, 1)
# Call the ufunc with 2 arguments (all will work)
print(my_ufunc([1, 2, 3], 1))
print(my_ufunc([1, 2, 3], [1]))
print(my_ufunc([1, 2, 3], [1, 2, 3]))
# Call the ufunc with 1 positional argument, omit the 2nd for which a default
# value was previously defined
# but it will not work :(
print(my_ufunc([1, 2, 3]))
TRACEBACK:
TypeError: my_func (vectorized)() takes from 2 to 3 positional arguments but 1 were given
>Solution :
numpy has overloaded all the arithmetic operators on numpy arrays (+, -, *, /, etc….), you just need to convert your list to a numpy array to use those operators.
import numpy as np
def my_func(x, y=1):
return x + y
lst1 = [1,2,3]
arr1 = np.array(lst1) # convert list to numpy array
arr2 = np.array([3,4,5]) # define and convert list to numpy array
print(my_func(arr1, arr2))
print(my_func(arr1))
[4,6,8]
[2,3,4]
you can check numpy quickstart and numpy broadcasting for a view on how numpy overrides a lot of operations for you.
as for you main issue, np.frompyfunc creates a wrapper function that just inspects and replicates the number of arguments, but doesn’t inspect the default arguments, but you don’t/shouldn’t need to use it anyway as it is much slower (and longer) than using numpy’s overloaded operators.