2

I have an numpy array R of dimension (n, n, n, 3) and a function f which takes a 1-D vector to a scalar. I need a new array A whose relationship with R is

A[i, j, k] = f(R[i, j, k, :])

How can I do this in numpy without three for statements.

3
  • This depends on what f is. Hopefully, it'll be as simple as adding axis arguments in a few places. Commented Feb 19, 2016 at 1:06
  • 1
    f is so complicated that I don't even want to post it here. Commented Feb 19, 2016 at 1:08
  • Anther 'trick' is to reshape R to 2d, so you index on just one axis, and slice the other. Then reshape the result back. In other words, temporarily 'flatten' the i,j,k dimensions. It won't save iteration steps, but should simplify the code. Commented Feb 19, 2016 at 5:56

1 Answer 1

2

Ideally, you'd do this by changing the implementation of f to use techniques that handle high-dimensional input appropriately. For example, you might change np.sum(whatever) to np.sum(whatever, axis=-1) to get a sum over the last axis instead of the whole array. This would produce the most efficient results, but it might be difficult or impossible, depending on f.

The slower, much easier answer is np.apply_along_axis:

A = np.apply_along_axis(f, -1, R)

This is prettier than 3 for loops, but it probably won't be any more efficient.

Sign up to request clarification or add additional context in comments.

2 Comments

Is np.vectorize more efficient than for loops?
Plus vectorize is tricky to apply when the function takes a 1d array instead of a scalar.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.