numpy.triu() method : How to use numpy.triu() Function in Python

NumPy triu() function is used to get a copy of a matrix with the elements below the k-th diagonal zeroed. The number of rows in the array. Diagonal above which to zero elements. k = 0 (the default) is the main diagonal, k < 0 is below it and k > 0 is above.

Numpy triu()

Numpy triu() is an inbuilt function that is used to return a copy of the array matrix with an element of the upper part of the triangle with respect to k. The triu() method takes two parameters and returns the upper triangle of the array matrix.

The triu() function is defined under  numpy, which can be imported as import numpy as np, and we can create multidimensional arrays and derive other mathematical statistics with the help of numpy, which is a library in Python.

Syntax

numpy.triu(array, k=0)

Parameters

  • array: It takes the input array.
  • k: It is an optional parameter with 0 as the default.

Return Value

The triu() function returns the upper triangle of the array matrix, which has the same datatype and same shape as the main array.


numpy.triu() method with Example

Example 1: Let us consider the following example 

# import numpy library
import numpy as np

# create an input matrix
x = np.matrix([[6, 7], [8, 9], [10, 11]])
print("Input of Matrix :", x)

# numpy.triu() function
y = np.triu(x, 1)

# Display Triu Values
print("Triu Elements: ", y)

Output

Input of Matrix :
[[ 6 7]
[ 8 9]
[10 11]]
Triu Elements:
[[0 7]
[0 0]
[0 0]]

Example 2: Let us take another example 

# import numpy library
import numpy as np

# create an input matrix
a = np.matrix([[11, 12, 13], [20, 21, 22], [44, 45, 46]])
print("Input of Matrix : ", a)

# numpy.triu() function
b = np.triu(a, -1)

# Display Triu Values
print("Triu Elements: ", b)

Output: 

Input of Matrix :
[[11 12 13]
[20 21 22]
[44 45 46]]
Triu Elements:
[[11 12 13]
[20 21 22]
[ 0 45 46]]

Happy Coding !!!

#numpy #python

5.70 GEEK