How to move items in a numpy array in Python?

I haven’t found a simple solution to move elements in a NumPy array.

Given an array, for example:

>>> A = np.arange(10).reshape(2,5)
>>> A
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])

and given the indexes of the elements (columns in this case) to move, for example [2,4], I want to move them to a certain position and the consecutive places, for example to p = 1, shifting the other elements to the right. The result should be the following:

array([[0, 2, 4, 1, 3],
       [5, 7, 9, 6, 8]])

Answer

You can create a mask m for the sorting order. First we set the columns < p to -1, then the to be inserted columns to 0, the remaining columns remain at 1. The default sorting kind 'quicksort' is not stable, so to be safe we specify kind='stable' when using argsort to sort the mask and create a new array from that mask:

import numpy as np

A = np.arange(10).reshape(2,5)
p = 1
c = [2,4]

m = np.full(A.shape[1], 1)
m[:p] = -1    # leave up to position p as is
m[c] = 0      # insert columns c

print(A[:,m.argsort(kind='stable')])
#[[0 2 4 1 3]
# [5 7 9 6 8]]