1

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]])
3
  • Make a new array using the appropriate column indexing. Commented Feb 3, 2021 at 8:50
  • A[:,[0,2,4,1,2,3]]? Commented Feb 3, 2021 at 10:10
  • yes, but then it is the same problem with the indexes. How can I do this automatically? Commented Feb 3, 2021 at 11:02

1 Answer 1

1

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]]
Sign up to request clarification or add additional context in comments.

2 Comments

I think quicksort is not stable.
@DiegoPalacios yes, my bad. I updated the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.