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

Overview

Python’s triu() function is used for the upper triangle of a given array.

Syntax

triu(m, k=0)

Parameter value

The triu() function takes the following parameter values:

  • m: This represents the array_like object or the input array.
  • k: This represents the diagonal above or below the main diagonal. K<0 is below the main diagonal, and k>0 is above the main diagonal. This is optional.

Return value

The triu() function returns an upper triangle of the same shape and data type as the array m passed to it.

Code example 1

import numpy as np
# creating an array
myarray = np.arange(9).reshape((3,3))
# implementing the triu() function
triuarray = np.triu(myarray, k=0)
print(myarray)
print(triuarray)

Code explanation

  • Line 1: we import the numpy library.
  • Line 4: we create an array myarray containing 9 arrange with a dimension of 3 by 3(i.e 3 rows and 3 columns) using the arange() function.
  • Line 7: we implement the triu() function on the array myarray using the main diagonal k = 0. The result is assigned to a new variable triuarray.
  • Line 9: we print the array myarray.
  • Line 10: we print the new array triuarray.

It is worth noting that in the code example above we returned an upper triangle of an array that starts from the main or default diagonal. For the main diagonal, k = 0.

Now let us return an upper triangle of an array below (k < 0) the main or default diagonal.

Code Example 2

import numpy as np
# creating an array
myarray = np.arange(9).reshape((3,3))
# implementing the triu() function
triuarray = np.triu(myarray, k=-1)
print(myarray)
print(triuarray)

Code Explanation

Similar to the first example but here we use a diagonal value which is below (k < 0) the main diagonal. This simply means that our upper triangle array will start before the main diagonal as can be seen in the code’s output.

Now let us return an upper triangle of an array above (k > 0) the main or default diagonal.

import numpy as np
# creating an array
myarray = np.arange(9).reshape((3,3))
# implementing the triu() function
triuarray = np.triu(myarray, k = 1)
print(myarray)
print(triuarray)

Code Explanation

Similar to the first example but here we use a diagonal value which is above (k > 0) the main diagonal. This simply means that the upper triangle array will start after the main diagonal as can be seen in the code’s output.

Free Resources