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<0is below the main diagonal, andk>0is 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 arraymyarray = np.arange(9).reshape((3,3))# implementing the triu() functiontriuarray = np.triu(myarray, k=0)print(myarray)print(triuarray)
Code explanation
- Line 1: we import the
numpylibrary. - Line 4: we create an array
myarraycontaining9arrange with a dimension of3 by 3(i.e3rows and3columns) using thearange()function. - Line 7: we implement the
triu()function on the arraymyarrayusing the main diagonalk = 0. The result is assigned to a new variabletriuarray. - 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 arraymyarray = np.arange(9).reshape((3,3))# implementing the triu() functiontriuarray = 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 arraymyarray = np.arange(9).reshape((3,3))# implementing the triu() functiontriuarray = 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.