将矩阵插入 python 中另一个矩阵的中心

insert matrix into the center of another matrix in python

有没有什么快速简单的方法可以使用 numpy 或 scipy 将一个小矩阵插入到另一个更大矩阵的中心(或任何其他 x,y 索引)?
也就是说,假设我有矩阵

A = [1 2]
    [3 4]

和矩阵

B =   [0 0 0 0 0 0]  
      [0 0 0 0 0 0]  
      [0 0 0 0 0 0]  
      [0 0 0 0 0 0]  
      [0 0 0 0 0 0]  
      [0 0 0 0 0 0]  

我想把A插入到B的中心:

C =   [0 0 0 0 0 0]  
      [0 0 0 0 0 0]  
      [0 0 1 2 0 0]  
      [0 0 3 4 0 0]  
      [0 0 0 0 0 0]  
      [0 0 0 0 0 0] 

您可以使用 numpy 的切片表示法。

nb = B.shape[0]
na = A.shape[0]
lower = (nb) // 2 - (na // 2)
upper = (nb // 2) + (na // 2)
B[lower:upper, lower:upper] = A