Element-wise apply array of functions to array of values in numpy, efficiently

Viewed 368

I have a numpy array with functions and another one with values:

f = np.array([np.sin,np.cos,lambda x: x**2])
x = np.array([0,0,3])

I want to apply each function to each element in x. This can be easily done as

np.array([F(X) for F,X in zip(f,x)])

Is there a more efficient way that does not involve a for loop? Something like just f(x) (which of course does not works).

1 Answers

You can use np.vectorize:

>>> def apply(func, arg):
        return func(arg)

>>> vectorized_apply = np.vectorize(apply)
>>> vectorized_apply(f, x)
array([0., 1., 9.])
Related