0

Suppose, I got a 2D (n \times 2*n) numpy array like below,

dat = np.array([[1,2,3,4],[5,6,7,8]])

I want to split it into two 2d array equally, and then create a 2d diagonal block array, like below,

a = dat[:,0:2]
b = dat[:,2:]
result = np.block([
    [a,               np.zeros((2, 2))],
    [np.zeros((2, 2)), b              ]
])

Is there any better way in numpy that I dont need to specify this part "np.zero((n,n))"

Nicolas H
  • 535
  • 3
  • 13

1 Answers1

2

Use scipy.linalg.block_diag

>>> import scipy.linalg
>>> scipy.linalg.block_diag(a, b)
array([[1, 2, 0, 0],
       [5, 6, 0, 0],
       [0, 0, 3, 4],
       [0, 0, 7, 8]])

Taken from this post

user15270287
  • 1,123
  • 4
  • 11