I want to apply a function that takes a 2D array (and returns one of the same shape) to each 2D slice of a 3D array. What's an efficient way of doing this? numpy.fromiter
returns a 1D array and numpy.fromfunction
needs to be applied to each coordinate individually.
Currently I am doing
foo = np.array([func(arg, bar2D) for bar2D in bar3D])
This gives me what I want, but the list comprehension is very slow. Also, func
is a 1D derivative with particular boundary conditions. numpy.gradient
only seems to do N-D derivatives with N the dimension of the array, but maybe there is another routine that will do the whole thing for me?
Edit: The list comprehension works, but I'm looking for a faster way of doing it. bar3D
can be large, up to (500,500,1000)
. All the numpy
routines I've found for applying functions to arrays seem to assume either the function or the array are 1D.