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, firstimport numpy.
Parameter value
The diagonal() function takes the following parameter values:
a: This represents thearray_likeobject 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 is0. This is optional.axis1: This represents the axis to be used as the first axis of the2Dsub-arrays from which the diagonals should be taken. The default value is0.axis2: This represents the axis to be used as the second axis of the2Dsub-arrays from which the diagonals should be taken. The default value is1.
Return value
The diagonal() function returns a diagonal array.
Code example
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)
Explanation
- Line 1: We import the
numpylibrary. - Line 4: We create a 2D array
myarrayof 9 elements with a dimension of3 by 3, that is3rows and3columns, using thearange()function. - Line 7: We implement the
diag()function on the arraymyarrayusing the main diagonalk = 0, defaultaxis1,0, and a defaultaxis2,0. The result is assigned to a new variablediagarray. - Line 9: We print the array
myarray. - Line 10: We print the new diagonal array
diagarray.