The diagonal()
function in Python is simply used to return a specified diagonal from a given 2D array.
numpy.diagonal(a, offset=0, axis1=0, axis2=1)
Note: To use
numpy.diagonal()
function, firstimport numpy
.
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
.The diagonal()
function returns a diagonal array.
import numpy as np# creating an arraymyarray = np.arange(9).reshape(3, 3)# implementing the diagonal() functiondiagarray = np.diagonal(myarray, 0, 0, 1)print(myarray)print(diagarray)
numpy
library.myarray
of 9 elements with a dimension of 3 by 3
, that is 3
rows and 3
columns, using the arange()
function.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
.myarray
.diagarray
.