3

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

4 Answers 4

3

You can use slicing and concatenation.

np.concatenate((a[:3], a[-3:], a[3:-3]))
Sign up to request clarification or add additional context in comments.

1 Comment

We just need to perform three number-swap operations. Your solution will will involve making copies of all the other (bigger) chunks of data too. Needless, don't you think?
2

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)

Comments

1

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]

Comments

0

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]

Comments

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.