How to efficiently flip a multidimensional numpy array?

Suppose I have an array

>>> a  
[[[0, 1, 2], [3, 4, 5], [6, 7, 8]], [[10, 11, 12], [13, 14, 15], [16, 17, 18]]]

that I want to turn the axis so that in the end

>>> aflipped  
[[[2, 1, 0], [5, 4, 3], [8, 7, 6]], [[12, 11, 10], [15, 14, 13], [18, 17, 16]]]

I would like to do this with any

>>> aflipped=a[::-1][::1][::1]

or

>>>> aflipped=flipud(a)

as I understand that it is extremely fast and (important) with low memory usage. My code ends up changing what the for loop is not perfect at all.

This is actually a 4D array where I just want to flip one axis, but it seems my parameters are limited to the first two axes. Is there an effective memory method?

+4
source share
1 answer

Something like that:

>>> a = np.array([[[0, 1, 2], [3, 4, 5], [6, 7, 8]], [[10, 11, 12], [13, 14, 15], [16, 17, 18]]])
>>> a[:,:,::-1]      #or a[..., ::-1]
array([[[ 2,  1,  0],
        [ 5,  4,  3],
        [ 8,  7,  6]],

       [[12, 11, 10],
        [15, 14, 13],
        [18, 17, 16]]])

Time comparison:

>>> %timeit a[:,:,::-1]
1000000 loops, best of 3: 1.53 µs per loop
>>> %timeit a[..., ::-1]
1000000 loops, best of 3: 1.06 µs per loop
+12
source

All Articles