2

I have a 2D numpy array of lambda functions. Each function has 2 arguments and returns a float.

What's the best way to pass the same 2 arguments to all of these functions and get a numpy array of answers out?

I've tried something like:

np.reshape(np.fromiter((fn(1,2) for fn in np.nditer(J,order='K',flags=["refs_ok"])),dtype = float),J.shape)

to evaluate each function in J with arguments (1,2) ( J contains the functions).

But it seems very round the houses, and also doesn't quite work... Is there a good way to do this?

A = J(1,2)

doesn't work!

1
  • 1
    Why is this an array? Why not a list (or list of lists)? It has to be an object dtype array anyways, so you can't do much math on it. And iteration on a list is faster. Commented Apr 13, 2018 at 16:48

2 Answers 2

1

You can use list comprehensions:

A = np.asarray([[f(1,2) for f in row] for row in J])

This should work for both numpy arrays and list of lists.

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

Comments

0

I don't think there is a really clean way, but this is reasonably clean and works:

import operator
import numpy as np

# create array of lambdas
a = np.array([[lambda x, y, i=i, j=j: x**i + y**j for i in range(4)] for j in range(4)])

# apply arguments 2 and 3 to all of them
np.vectorize(operator.methodcaller('__call__', 2, 3))(a)
# array([[ 2,  3,  5,  9],
#        [ 4,  5,  7, 11],
#        [10, 11, 13, 17],
#        [28, 29, 31, 35]])

Alternatively, and slightly more flexible:

from types import FunctionType

np.vectorize(FunctionType.__call__)(a, 2, 3)
# array([[ 2,  3,  5,  9],
#        [ 4,  5,  7, 11],
#        [10, 11, 13, 17],
#        [28, 29, 31, 35]])

1 Comment

Here vectorize makes iteration over the 2d a easier, but does not improved speed (compared to an explicit loop).

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.