Reputation: 7235
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
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
Reputation: 1327
You can use slicing and concatenation.
np.concatenate((a[:3], a[-3:], a[3:-3]))
Upvotes: 3
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
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