Stack vertically 5 2D-arrays in diagonal to build a whole 2d-array

巧了我就是萌 提交于 2019-12-02 01:28:07

You could use scipy.sparse.block_diag:

>>> AtoE = np.add.outer(np.arange(5, 10), np.zeros((3, 3), int))
>>> scipy.sparse.block_diag(AtoE).A
array([[5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 7, 7, 7, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 7, 7, 7, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 7, 7, 7, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9]], dtype=int64)

Sparse storage may be a good idea, anyway.

Alternatively, here is a more direct method in case you definitely want to use dense arrays:

>>> A = AtoE[0]
>>> N, N = A.shape
>>> k = len(AtoE)
>>> out = np.zeros((k, N, k, N), A.dtype)
>>> np.einsum('ijik->ijk', out)[...] = AtoE
>>> out.reshape(k*N, k*N)
array([[5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 7, 7, 7, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 7, 7, 7, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 7, 7, 7, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9]])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!