Efficient evaluation of a function at every cell of a NumPy array Efficient evaluation of a function at every cell of a NumPy array python python

Efficient evaluation of a function at every cell of a NumPy array


You could just vectorize the function and then apply it directly to a Numpy array each time you need it:

import numpy as npdef f(x):    return x * x + 3 * x - 2 if x > 0 else x * 5 + 8f = np.vectorize(f)  # or use a different name if you want to keep the original fresult_array = f(A)  # if A is your Numpy array

It's probably better to specify an explicit output type directly when vectorizing:

f = np.vectorize(f, otypes=[np.float])


A similar question is: Mapping a NumPy array in place.If you can find a ufunc for your f(), then you should use the out parameter.


If you are working with numbers and f(A(i,j)) = f(A(j,i)), you could use scipy.spatial.distance.cdist defining f as a distance between A(i) and A(j).