How to create a diagonal array from an existing array in numpy

I am trying to make a diagonal numpy array from:

[1,2,3,4,5,6,7,8,9]

      

Expected Result:

[[ 0,  0,  1,  0,  0],
 [ 0,  0,  0,  2,  0],
 [ 0,  0,  0,  0,  3],
 [ 4,  0,  0,  0,  0],
 [ 0,  5,  0,  0,  0],
 [ 0,  0,  6,  0,  0],
 [ 0,  0,  0,  7,  0],
 [ 0,  0,  0,  0,  8],
 [ 9,  0,  0,  0,  0]]

      

What would be an efficient way to do this?

+3


source to share


2 answers


You can use integer array indexing to set the specified output elements:



>>> import numpy as np
>>> a = [1,2,3,4,5,6,7,8,9]
>>> arr = np.zeros((9, 5), dtype=int)           # create empty array
>>> arr[np.arange(9), np.arange(2,11) % 5] = a  # insert a 
>>> arr
array([[0, 0, 1, 0, 0],
       [0, 0, 0, 2, 0],
       [0, 0, 0, 0, 3],
       [4, 0, 0, 0, 0],
       [0, 5, 0, 0, 0],
       [0, 0, 6, 0, 0],
       [0, 0, 0, 7, 0],
       [0, 0, 0, 0, 8],
       [9, 0, 0, 0, 0]])

      

+2


source


Inspired np.fill_diagonal

, which can wrap but not displace:

In [308]: arr=np.zeros((9,5),int)
In [309]: arr.flat[2:45:6]=np.arange(1,10)
In [310]: arr
Out[310]: 
array([[0, 0, 1, 0, 0],
       [0, 0, 0, 2, 0],
       [0, 0, 0, 0, 3],
       [0, 0, 0, 0, 0],
       [4, 0, 0, 0, 0],
       [0, 5, 0, 0, 0],
       [0, 0, 6, 0, 0],
       [0, 0, 0, 7, 0],
       [0, 0, 0, 0, 8]])

      



(although for some reason this has the 4th all null string).

def fill_diagonal(a, val, wrap=False):
    ...       
    step = a.shape[1] + 1
    # Write the value out into the diagonal.
    a.flat[:end:step] = val

      

+1


source







All Articles