What is the diag() function from NumPy in Python?
Overview
The diag() function in Python is used to extract a diagonal array.
Syntax
numpy.diag(v, k=0)
Parameters
The diag() function takes the following parameter values:
v: This represents thearray_likeobject.k: This represents the diagonal in question. The default is0.k>0for diagonals above the main diagonal andk<0for diagonals below the main diagonal.
Return value
The diag() function returns a constructed diagonal array or an extracted diagonal array.
Example
import numpy as np# creating an arraymyarray = np.arange(9).reshape((3,3))# implementing the diag() functiondiagarray = np.diag(myarray, k=0)print(myarray)print(diagarray)
Explanation
- Line 1: We import the
numpylibrary. - Line 4: We create an array
myarraythat contains9values with a dimension of 3x3 (3rows and3columns) using thearange()function. - Line 7: We implement the
diag()function on the arraymyarrayusing the main diagonalk=0. The result is assigned to a new variable,diagarray. - Line 9: We print the array
myarray. - Line 10: We print the new diagonal array
diagarray.