Reputation: 1913
I want my inserted array to replace as many elements in the target array as there are in this replacing array, just like this:
x = np.array([1, 2, 3, 4, 5])
y = np.array([6, 7, 8])
# Doing unknown stuff
x = array([6, 7, 8, 4, 5])
Is there some numpy method or something tricky to implement this?
I would also like to know if this can be done despite of how the lengths of the arrays relate to each other, for instance like this:
x = np.array([1, 2])
y = np.array([6, 7, 8])
# Doing unknown stuff
x = array([6, 7])
Upvotes: 1
Views: 63
Reputation: 120391
Another solution
x[:len(y)] = y[:len(x)]
First case
>>> x
array([6, 7, 8, 4, 5])
Second case
>>> x
array([6, 7])
Upvotes: 4
Reputation: 566
Numpy is relatively fast:
x = np.array([1, 2, 3, 4, 5])
y = np.array([6, 7, 8])
xnew = np.concatenate((y, x[len(y):]))
>>> xnew
array([6, 7, 8, 4, 5])
Upvotes: 2