Kaiyakha
Kaiyakha

Reputation: 1913

A tricky way of replacing insertion of a numpy array into another array

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

Answers (3)

Corralien
Corralien

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

velenos14
velenos14

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

Joep
Joep

Reputation: 834

Here is one solution:

x = np.append(y, x[len(y):])

Upvotes: 2

Related Questions