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

How to create a diagonal array from an existing array in numpy… here is a solution to the problem.

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

I’m trying to create a diagonal numpy array from:

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

Expected Results:

[[ 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 is an effective way to do this?

Solution

You can use integer array indexing sets the specified element 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]])

Related Problems and Solutions