I\'m working with an n-dimensional array, and I\'d like a way to reverse a numbered dimension. So rather than
rev = a[:,:,::-1]
I\'d like to be
Turns out this can be done with slice
, for which :
is shorthand in some contexts. The trick is to build the index object as a tuple of slices:
import numpy as np
def reverse(a, axis=0):
idx = [slice(None)]*len(a.shape)
idx[axis] = slice(None, None, -1)
return a[idx]
a = np.arange(24).reshape(2,3,4)
print reverse(a, axis=2)
With Ellipsis
this can be collapsed into a one-liner:
a[[slice(None)]*axis + [slice(None, None, -1)] + [Ellipsis]]