Home > Back-end >  Move all array elements one space up in python NumPy
Move all array elements one space up in python NumPy

Time:11-13

I'm trying to do a sorting algorithm and I need to do something like this:

arr = numpy.array([2,4,5,6])
#some function here or something
array([5,2,4,6])
#element "5" moved from position 3 to 1, and all of the others moved up one position

What I mean is I want to change an element's position (index) and move all the other elements up one position. Is this possible?

CodePudding user response:

You could use numpy.roll with a subset assignment:

arr = numpy.array([2,4,5,6])

arr[:3] = numpy.roll(arr[:3],1)

print(arr)
[5 2 4 6]

CodePudding user response:

If you know the position/index of the element to be shifted, then you could do:

indx = 2
np.r_[arr[indx], np.delete(arr, indx)]
Out[]: array([5, 2, 4, 6])

CodePudding user response:

You could do this in-place without the need of creating first an intermediate array of n-1 elements and then creating another final array by concatenation. Instead, you could try this:

idx = 2
tmp = arr[idx]
arr[1:idx 1] = arr[0:idx]
arr[0] = tmp

So there are more than one ways of doing this, and the choice depends upon your algorithm's constraints.

  • Related