5

Let's say I have a multidimensional array with a shape that I don't know until runtime.

How can I reverse it along a given axis k, also not known until runtime?

The notation somearray[:,:,::-1,:,:] relies on static dimension references, as in this other SO question, so I can't use it here.

2 Answers 2

9

You can either construct a tuple of slice objects such as @ali_m suggests, or do something like this:

reversed_arr = np.swapaxes(np.swapaxes(arr, 0, k)[::-1], 0, k)

This places the desired axis at the front of the shape tuple, then reverses that first axis, and then returns it to its original position.

Some people think this approach lacks readability, but I disagree.

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

1 Comment

Since it returns a view, array is not copied, nice approach. Also, I found this approach the most elegant when array on LHS needs to be changed in given axis.
7

I would use a tuple of slice objects for this:

def reversedim(M,k=0):
    idx = tuple((slice(None,None,-1) if ii == k else slice(None) 
            for ii in xrange(M.ndim)))
    return M[idx]

1 Comment

@NilsWerner I don't think so. See here - "Note that slices of arrays do not copy the internal array data but also produce new views of the original data."

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.