鉴于N 2d numpy数组,有没有一种简洁的方法可以在对角线上“堆叠”或“闩锁”它们,用0填充任何新的插槽?例如。给出:
arr1 = np.array([[1, 2],
[3, 4]])
arr2 = np.array([[9, 8, 7],
[6, 5, 4],
[3, 2, 1]])
我想创建:
arr = np.array([[1, 2, 0, 0, 0],
[3, 4, 0, 0, 0],
[0, 0, 9, 8, 7],
[0, 0, 6, 5, 4],
[0, 0, 3, 2, 1]])
答案 0 :(得分:5)
scipy.linalg.block_diag(arr1, arr2)
需要任意多个参数:
scipy.linalg.block_diag(*list_of_arrays)
答案 1 :(得分:3)
尝试:
14:07:55,666 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) JBAS013412: Timeout after [300] seconds waiting for service container stability. Operation will roll back. St
ep that first updated the service container was 'add' at address '[
("core-service" => "management"),
("management-interface" => "native-interface")
]'
并且,为了验证它是否有效,我们可以显示>>> arr = np.zeros((5, 5))
>>> arr[:2, :2] = arr1
>>> arr[2:, 2:] = arr2
:
arr
答案 2 :(得分:1)
我刚刚发现这似乎完全符合我的需要:
https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.linalg.block_diag.html
>> from scipy.linalg import block_diag
>>> A = [[1, 0],
... [0, 1]]
>>> B = [[3, 4, 5],
... [6, 7, 8]]
>>> C = [[7]]
>>> block_diag(A, B, C)
[[1 0 0 0 0 0]
[0 1 0 0 0 0]
[0 0 3 4 5 0]
[0 0 6 7 8 0]
[0 0 0 0 0 7]]
答案 3 :(得分:1)
np
有一个相对较新的block
函数,用于连接嵌套的数组列表。但它需要指定零填充块:
In [15]: np.block([[arr1, np.zeros((2,3),int)], [np.zeros((3,2),int), arr2]])
Out[15]:
array([[1, 2, 0, 0, 0],
[3, 4, 0, 0, 0],
[0, 0, 9, 8, 7],
[0, 0, 6, 5, 4],
[0, 0, 3, 2, 1]])