numpy.triu Method in Python



The numpy.triu() method can be used to get the upper triangle of an array. Its syntax is as follows −

Syntax

numpy.triu(m, k=0)

where,

  • m - number of rows in the array.

  • k - It is the diagonal. Use k=0 for the main diagonal. k < 0 is below the main diagonal and k > 0 is above it.

It returns a copy of the array after replacing all the elements above the kth diagonal with zero.

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

It will generate the following 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

It will generate the following output −

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

Advertisements