multidimensional numpy array -- reverse along a given axis multidimensional numpy array -- reverse along a given axis numpy numpy

multidimensional numpy array -- reverse along a given axis


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.


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]