emax
emax

Reputation: 7235

Python: how to move values in an array from some position to another?

I have an a array of values

a = np.array([0,3,4,5,12,3,78,53,52])

I would like to move the last three elements in the array starting from the index 3 in order to have

a 
array([ 0, 3, 4, 78, 53, 52, 5, 12, 3])

Upvotes: 3

Views: 7268

Answers (4)

fountainhead
fountainhead

Reputation: 3722

This is just a number-swapping problem -- not a numpy problem.

Any solution to this problem that involves numpy functions such as concatenate, delete, insert, or even slicing, is inefficient, involving unnecessary copying of data.

This should work, with minimum copying of data:

a[3],a[4],a[5], a[-3],a[-2],a[-1] = a[-3],a[-2],a[-1], a[3],a[4],a[5]

print(a)

Output:

[ 0  3  4 78 53 52  5 12  3]

Upvotes: 1

Sven-Eric Krüger
Sven-Eric Krüger

Reputation: 1327

You can use slicing and concatenation.

np.concatenate((a[:3], a[-3:], a[3:-3]))

Upvotes: 3

Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11073

Try this using np.delete() and np.insert():

a = np.array([0,3,4,5,12,3,78,53,52])
index = 6
another_index = 0
v = a[index]
np.delete(a,index)
np.insert(a, another_index, v)

Upvotes: 2

zabop
zabop

Reputation: 7852

Starting with

a = np.array([0,3,4,5,12,3,78,53,52])

You can just do:

newa=[]
for index, each in enumerate(a):
    if index<3:
        newa.append(a[index])
    else:
        newa.append(a[3+index%6])

giving the resulting newa to be:

[0, 3, 4, 78, 53, 52, 5, 12, 3]

Upvotes: 0

Related Questions