1
$\begingroup$

I have a numpy function f that takes arrays as arguments and a 3D array x[a,b,c].

I would like to evaluate the function f along a specific column. A long-winded way could be with comprehensions:

y = [ [ f(x[a][b])  for a in range(len(x)) ] for b in range(len(x[0]))]
y = np.array(y)

Is there a numpy way of doing this with broadcasting?

$\endgroup$
1
$\begingroup$

np.apply_along_axis(f, 2, x).T

| cite | improve this answer | |
$\endgroup$
0
$\begingroup$

This is a simpler comprehension:

numpy.array([[f(row) for row in layer] for layer in x]).T

or more concisely,

numpy.array([map(f,layer) for layer in x]).T

Note that I reproduced the transpose from your sample code. You can avoid the nested comprehension with cryptic reshaping:

numpy.reshape(map(f,x.reshape(numpy.prod(x.shape[:2]), x.shape[2])),x.shape[:2]).T
| cite | improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.