Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add small 2D array to larger array?

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

like image 377
the dood Avatar asked Nov 23 '13 00:11

the dood


1 Answers

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]]
like image 89
ArtemB Avatar answered Sep 25 '22 15:09

ArtemB