9

I have a larger 2D array, and I would like to add a smaller 2D array.

from numpy import *
x = range(25)
x = reshape(x,(5,5))
print x
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]]
y = [66,66,66,66]
y = reshape(y,(2,2))
print y
[[66 66]
 [66 66]]

I would like to add the values from array y to x starting at 1,1 so that x looks like this:

[[ 0  1  2  3  4]
 [ 5 72 73  8  9]
 [10 77 78 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]]

Is this possible with slicing? Can someone please suggest the correct formatting of the slice statement to achieve this?

Thanks

2 Answers 2

12

Yes, you can use slicing on numpy arrays:

In [20]: x[1:3,1:3] += y

In [21]: print x
[[ 0  1  2  3  4]
 [ 5 72 73  8  9]
 [10 77 78 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]]
Sign up to request clarification or add additional context in comments.

Comments

8
x[1:3, 1:3] += y

Add y in-place to the slice of x you want to modify. Note that numpy indexing counts from 0, not 1. Also, note that for this particular choice of y,

x[1:3, 1:3] += 66

will achieve the same effect in a simpler manner.

2 Comments

Same solution s suggested by @ArtemB. Thanks fro the quick reply.
+1 for pointing that a scalar could've been used. It would potentially be faster for large operations.

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.