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(), first import 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 is 0, which represents the main diagonal.
  • axis1, axis2: These represent the axes to be used as the first and second axis of the 2-D sub-arrays from which the diagonals should be taken. The default values are the first two values of the a parameter.
  • 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 array
myarray = np.arange(9).reshape((3,3))
# implementing the diag() function
sumdiag = np.trace(myarray, dtype = float)
print(myarray)
print(sumdiag)

Code 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 trace() function on the array myarray using the default value of the parameters. myarray will be passed as a float data type. The result is assigned to a new variable sumdiag.
  • Line 9: We print the array myarray.
  • Line 10: We print the new diagonal array sumdiag.

Note: The output 12 was obtained from the sum of the diagonal 0, 4, and 8.