Greedo
Greedo

Reputation: 5543

Pass argument to array of functions

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!

Upvotes: 2

Views: 182

Answers (2)

Paul Panzer
Paul Panzer

Reputation: 53029

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

Upvotes: 0

Eolmar
Eolmar

Reputation: 810

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.

Upvotes: 1

Related Questions