What is the numpy.trace() function from NumPy in Python?
Overview
The trace() function in Python is simply used to return the sum along the diagonals of a given array.
Syntax
numpy.trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None)
Note: To use
trace(), firstimport numpy.
Required parameter value
The trace() function takes a mandatory parameter value a, which represents the array_like object from which the diagonals are taken.
Optional parameter value
The trace() function takes the following optional parameters:
offset: This represents the offset of the diagonal from the main diagonal. It can take a positive or negative value. The default value is0, which represents the main diagonal.axis1,axis2: These represent the axes to be used as the first and second axis of the2-Dsub-arrays from which the diagonals should be taken. The default values are the first two values of theaparameter.dtype: This represents the data type of the output array and the accumulator where the elements are summed.out: This represents the array into which the output is placed.
Return value
The trace() function returns a sum along the diagonals of an array.
Code example
import numpy as np# creating an arraymyarray = np.arange(9).reshape((3,3))# implementing the diag() functionsumdiag = np.trace(myarray, dtype = float)print(myarray)print(sumdiag)
Code explanation
- Line 1: We import the
numpylibrary. - Line 4: We create a 2D array
myarrayof 9 elements with a dimension of3 by 3, that is,3rows and3columns, using thearange()function. - Line 7: We implement the
trace()function on the arraymyarrayusing the default value of the parameters.myarraywill be passed as a float data type. The result is assigned to a new variablesumdiag. - Line 9: We print the array
myarray. - Line 10: We print the new diagonal array
sumdiag.
Note: The output
12was obtained from the sum of the diagonal0,4, and8.