3

I have an application where I need to reverse the elements along one axis of a NumPy array according to some stride. As an example, let's consider that I have the following array

In [1]: import numpy as np

In [2]: a = np.array([[1,2],[3,4],[5,6],[7,8]])

In [3]: a
Out[3]: 
array([[1, 2],
       [3, 4],
       [5, 6],
       [7, 8]])

I want to reverse this array along the first axis (axis=0) with a stride of 2. In other words, I want to quickly get the following array:

Out[4]: 
array([[3, 4],
       [1, 2],
       [7, 8],
       [5, 6]])

Is there a quick way to do this with a built-in NumPy routine?

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
wbinventor
  • 345
  • 1
  • 4
  • 13
  • "... reverse the elements *along one axis* ... according to *some stride*." How general is the problem? Is the example (reversing pairs along the first axis) the only case you are interested in? – Warren Weckesser Sep 29 '15 at 02:16
  • It is actually much more general than I alluded to in my description. In most scenarios I need to be able to reverse only along the first axis of an n-dimensional array, but the stride is arbitrary (in this case I simplified it to only 2). – wbinventor Sep 29 '15 at 04:59

1 Answers1

4

Reshape to a 3d array; reverse one dimension; return to 2d:

In [51]: a = np.array([[1,2],[3,4],[5,6],[7,8]])
In [52]: a
Out[52]: 
array([[1, 2],
       [3, 4],
       [5, 6],
       [7, 8]])
In [53]: a.reshape(2,2,2)
Out[53]: 
array([[[1, 2],
        [3, 4]],

       [[5, 6],
        [7, 8]]])
In [54]: a.reshape(2,2,2)[:,::-1,:]
Out[54]: 
array([[[3, 4],
        [1, 2]],

       [[7, 8],
        [5, 6]]])
In [55]: a.reshape(2,2,2)[:,::-1,:].reshape(4,2)
Out[55]: 
array([[3, 4],
       [1, 2],
       [7, 8],
       [5, 6]])
hpaulj
  • 221,503
  • 14
  • 230
  • 353