Lets say you have a p x q numpy 2d array A, here is a sample with (p,q) as (3,4):
In []: A = np.arange(1,13).reshape(4,3)
In []: A
Out[]:
array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])
Step 1:
To insert a diagonal of zeros, it will require making a new 2d array of shape p x q+1.
Before this we create a 2d array with column index values of non-diagonal elements for the new 2d array like this
In []: columnIndexArray = np.delete(np.meshgrid(np.arange(q+1), np.arange(p))[0], np.arange(0, p * (q+1), q+2)).reshape(p,q)
The output of the above will look as follows:
In []: columnIndexArray
Out[]:
array([[1, 2, 3],
[0, 2, 3],
[0, 1, 3],
[0, 1, 2]])
Step 2:
Now construct p x q+1 2d array of zeros like this
In []: B = np.zeros((p,q+1))
In []: B
Out[]:
array([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]])
Step 3:
Now assign the non diagonal elements with the values from A
In []: B[np.arange(p)[:,None], columnIndexArray] = A
In []: B
Out[]:
array([[ 0., 1., 2., 3.],
[ 4., 0., 5., 6.],
[ 7., 8., 0., 9.],
[ 10., 11., 12., 0.]])
Note:
To make your code dynamic replace p with A.shape[0] and q with A.shape[1] respectively.