2

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).

4
  • Do you want to avoid writing a for loop, or do you want to avoid executing a for loop (say, via vectorisation)? Commented Jul 9, 2021 at 11:10
  • Avoid executing the for loop and replace it for some more efficient vectorized way. Commented Jul 9, 2021 at 11:12
  • Since you are applying the functions to scalar values, using list and math functions instead of numpy will be faster. List iterate faster, and math.sin(1) is faster than np.sin(1). Commented Jul 9, 2021 at 15:54
  • 1
    Your f array is object dtype. The fast, no-loop, compiled methods work with numeric dtypes. object dtype is effectively a list - the elements are references to objects. The vaunted numpy "vectorization" means applying compiled methods to the arrays, moving the loops to compiled code. Commented Jul 9, 2021 at 15:56

1 Answer 1

1

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.])
Sign up to request clarification or add additional context in comments.

3 Comments

From the documentation: "The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.". I guess there is no efficient way of doing what I want.
It should be mentioned, for loop is not always inefficient. Depending on the number of entries you have, for loop can sometimes prove to be more efficient that np operations. This answer just saves you writing an explicit for loop, nothing more.
Since f is object dtype, you should get a bit better speed with np.frompyfunc. That's more competitive with the plain list comprehension in speed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.