1

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

3 Answers 3

4

Another solution

x[:len(y)] = y[:len(x)]

First case

>>> x
array([6, 7, 8, 4, 5])

Second case

>>> x
array([6, 7])
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect! Thanks!
What do you mean by "not the same"? The memory address of x will not be modified only the replaced cells.
2

Here is one solution:

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

1 Comment

Thanks, still please check out the second question I have appended
2

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

1 Comment

Thanks, yet the question has been updated

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.