Search code examples
pythonarraysnumpydiagonal

How to create diagonal array from 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 of doing this?


Solution

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

    >>> 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]])