如何将小型2D阵列添加到更大的阵列?

the*_*ood 4 python arrays numpy slice

我有一个更大的2D数组,我想添加一个更小的2D数组.

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]]
Run Code Online (Sandbox Code Playgroud)

我想将数组中的值添加yx起始位置1,1,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]]
Run Code Online (Sandbox Code Playgroud)

切片可能吗?有人可以建议切片语句的正确格式来实现这一点吗?

谢谢

use*_*ica 6

x[1:3, 1:3] += y
Run Code Online (Sandbox Code Playgroud)

将y就地添加到要修改的x切片中.请注意,numpy索引从0开始计数,而不是1.另外,请注意,对于y的这个特定选择,

x[1:3, 1:3] += 66
Run Code Online (Sandbox Code Playgroud)

将以更简单的方式达到同样的效果.

  • +1表示可以使用标量.大型操作可能会更快. (4认同)

Art*_*emB 5

是的,您可以对numpy数组使用切片:

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]]
Run Code Online (Sandbox Code Playgroud)