This method is similar to np.diag .
Method:
np.diagflat(v, k=0)
Constructs a 2D array with the input vector placed on the diagonal, with an offset k.
Returns:
np.ndarray
Parameters:
v: array-like-
A 1D array or list.
import numpy as np
result = np.diagflat(v=[[1], [2], [3]])
print(result)
'''
Output:
[[1 0 0]
[0 2 0]
[0 0 3]]
'''
k: int, Optional-
The diagonal offset (default 0). A positive value refers to an upper diagonal, and a negative value to a lower diagonal.
k = 0 (default) +
The diagonal offset is 0,0.
import numpy as np
result = np.diagflat(v=[[1], [2], [3]], k=0)
print(result)
'''
Output:
[[1 0 0]
[0 2 0]
[0 0 3]]
'''
k = 1 +
The diagonal offset is 0,1.
import numpy as np
result = np.diagflat(v=[[1], [2], [3]], k=1)
print(result)
'''
Output:
[[0 1 0 0]
[0 0 2 0]
[0 0 0 3]
[0 0 0 0]]
'''
k = -1 +
The diagonal offset is 1,0.
import numpy as np
result = np.diagflat(v=[[1], [2], [3]], k=-1)
print(result)
'''
Output:
[[0 0 0 0]
[1 0 0 0]
[0 2 0 0]
[0 0 3 0]]
'''