What is the numpy.diagonal() function from NumPy in Python?

Overview

The diagonal() function in Python is simply used to return a specified diagonal from a given 2D array.

Syntax

numpy.diagonal(a, offset=0, axis1=0, axis2=1)

Note: To use numpy.diagonal() function, first import numpy.

Parameter value

The diagonal() function takes the following parameter values:

  • a: This represents the array_like object from which the diagonal is taken.
  • offset: This represents the offset to the diagonal from the main diagonal. It could take a negative or positive integer value. The default to the main diagonal is 0. This is optional.
  • axis1: This represents the axis to be used as the first axis of the 2D sub-arrays from which the diagonals should be taken. The default value is 0.
  • axis2: This represents the axis to be used as the second axis of the 2D sub-arrays from which the diagonals should be taken. The default value is 1.

Return value

The diagonal() function returns a diagonal array.

Code example

import numpy as np
# creating an array
myarray = np.arange(9).reshape(3, 3)
# implementing the diagonal() function
diagarray = np.diagonal(myarray, 0, 0, 1)
print(myarray)
print(diagarray)

Explanation

  • Line 1: We import the numpy library.
  • Line 4: We create a 2D array myarray of 9 elements with a dimension of 3 by 3, that is 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, default axis1, 0, and a default axis2, 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