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

南楼画角 提交于 2019-12-10 17:17:27

问题


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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/20157040/how-can-i-add-small-2d-array-to-larger-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!