1

I have an array farr of functions, say

import numpy as np
farr=np.array([(lambda x, y: x+y) for n in range(5)])

(in reality, the functions are all different splines) Now, I would like one function f that returns the result of all the functions in farr as an array. Basically this:

def f(x, y):
    return np.array([f(x, y) for f in farr])

Can this be done in a more efficient way?

4
  • and what did you get with this code ? What result did you expect? Use some example data to show expected result. Commented Nov 20, 2019 at 16:21
  • @furas my code works, but I wonder if this is the most efficient way Commented Nov 20, 2019 at 16:32
  • 1
    If farr is a list instead of an array it should iterate a bit faster. Commented Nov 20, 2019 at 16:45
  • frompyfunc often provides a modest improvement over iteration (up to 2x). A possible use: fn=np.frompyfunc(lambda f,x,y:f(x,y),3,1), and fn(farr[:,None],x,y). Commented Nov 20, 2019 at 16:54

1 Answer 1

2

Another way is to use map:

x = 3
y = 3
value = list(map(lambda f: f(x,y), farr))

For more details see map doc. On my machine this is a tiny bit more efficient (~20% faster)

Sign up to request clarification or add additional context in comments.

1 Comment

I like this. Typically, I think of mapping a function over some value, but here I "map the values" over some functions.

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.