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

Time:09-17

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

CodePudding user response:

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])

CodePudding user response:

This should work (assumin you have a even number of elements, otherwise you might want to check this before)

x = x.reshape((len(x)//2, 2)) #split in two wolumns
x[:,0], x[:,1] = x[:,1], x[:,0].copy() # switch the columns
x = x.reshape(2*len(x)) # reshape back in a 1D array

CodePudding user response:

You can do:

import numpy as np
arr = np.array([8,7,6,5,4,3,2,1])
result = np.vstack((arr[1::2], arr[::2])).T.flatten()

output:
array([7, 8, 5, 6, 3, 4, 1, 2])
  • Related