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 the array_like object.
  • k: This represents the diagonal in question. The default is 0. k>0 for diagonals above the main diagonal and k<0 for 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 array
myarray = np.arange(9).reshape((3,3))
# implementing the diag() function
diagarray = np.diag(myarray, k=0)
print(myarray)
print(diagarray)

Explanation

  • Line 1: We import the numpy library.
  • Line 4: We create an array myarray that contains 9 values with a dimension of 3x3 (3 rows and 3 columns) using the arange() function.
  • Line 7: We implement the diag() function on the array myarray using the main diagonal k=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.

Free Resources