Search code examples
pythonarraysnumpymatrixnumpy-ndarray

How to reverse a numpy array and then also switch each 'pair' of positions?


For example, how would you do this sequence of operations on a np 1D array, x:

  1. [1,2,3,4,5,6,7,8]

  2. [8,7,6,5,4,3,2,1]

  3. [7,8,5,6,3,4,1,2]

The transition from state 1 to state 2 can be done with numpy.flip(x):

x = numpy.flip(x)

How can you go from this intermediate state to the final state, in which each 'pair' of positions switches positions

Notes: this is a variable length array, and will always be 1D


Solution

  • It is assumed that the length is always even. At this time, you only need to reshape, reverse and flatten:

    >>> ar = np.arange(1, 9)
    >>> ar.reshape(-1, 2)[::-1].ravel()
    array([7, 8, 5, 6, 3, 4, 1, 2])
    

    This always creates a copy, because the elements in the original array cannot be continuous after transformation, but ndarray.ravel() must create a continuous view.

    If it is necessary to transition from state 2 to state 3:

    >>> ar = ar[::-1]
    >>> ar    # state 2
    array([8, 7, 6, 5, 4, 3, 2, 1])
    >>> ar.reshape(-1, 2)[:, ::-1].ravel()
    array([7, 8, 5, 6, 3, 4, 1, 2])