Problem
I have an
ndarray
, defined byarr
that is ann
-dimensional cube with lengthm
in each dimension.I want to act a function,
func
, by slicing along the dimensionn=0
and taking eachn-1
-dim slice as an input to the function.
This seems to work for map()
but I can't find a numpy
variant that is appropriate. np.vectorise
seems to split the n-1
-tensor into individual scalar entries. Neither apply_along_axis
or apply_over_axes
seem appropriate either.
My problem is such that I need to pass arbitrary functions as inputs so I do not see a solution with einsum
being feasible either.
Question
- Do you know the best
numpy
alternative to usingnp.asarray(map(func, arr))
?
Example
I define an example array, arr
as a 4
-dim cube (or 4-tensor) by:
m, n = 3, 4
arr = np.arange(m**n).reshape((m,)*n)
I define an example function f
,
def f(x):
"""makes it obvious how the np.ndarray is being passed into the function"""
try: # perform an op using x[0,0,0] which is expected to exist
i = x[0,0,0]
except:
print '\nno element x[0,0,0] in x: \n{}'.format(x)
return np.nan
return x-x+i
The expected result, res
, from this function would remain the same shape but would satisfy the following:
print all([(res[i] == i*m**(n-1)).all() for i in range(m)])
This works with the default map()
function,
res = np.asarray(map(f, a))
print all([(res[i] == i*m**(n-1)).all() for i in range(m)])
True
I would expect np.vectorize
to work in the same way as map()
but it acts in scalar entries:
res = np.vectorize(f)(a)
no element x[0,0,0] in x:
0
...