Inverse arbitrary measurement in ndarray

I am working with an n-dimensional array and I need a way to change the numerical dimension. Therefore, instead of

rev = a[:,:,::-1] 

I would like to write

 rev = a.reverse(dimension=2) 

or something similar. I can not find examples that do not depend on the previous syntax.

+7
source share
3 answers

For those who are faced with this in the future:

Numpy 1.12+ has a function np.flip(array, dimension) , which runs exactly as requested. Even better, it returns a representation of the data, not a copy, and this happens in constant time.

+1
source

If you look at the numpy (python) source code, you will find the trick they use to write functions that work on a particular axis is to use np.swapaxes to put the target axis at axis = 0 . Then they write code that runs on 0-axis , and then use np.swapaxes again to return 0-axis to its original position.

You can do it like this:

 import numpy as np def rev(a, axis = -1): a = np.asarray(a).swapaxes(axis, 0) a = a[::-1,...] a = a.swapaxes(0, axis) return a a = np.arange(24).reshape(2,3,4) print(rev(a, axis = 2)) 

gives

 [[[ 3 2 1 0] [ 7 6 5 4] [11 10 9 8]] [[15 14 13 12] [19 18 17 16] [23 22 21 20]]] 
+9
source

It turns out that this can be done using slice , for which : is a shorthand in some contexts. The trick is to create an 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 folded into a single line:

 a[[slice(None)]*axis + [slice(None, None, -1)] + [Ellipsis]] 
+6
source

All Articles