w3resource

NumPy: Extract upper triangular part of a NumPy matrix

NumPy: Array Object Exercise-153 with Solution

Write a NumPy program to extract upper triangular part of a NumPy matrix.

Sample Solution:

Python Code:

import numpy as np
num = np.arange(18)
arr1 = np.reshape(num, [6, 3])
print("Original array:")
print(arr1)
result  = arr1[np.triu_indices(3)]
print("\nExtract upper triangular part of the said array:")
print(result)
result  = arr1[np.triu_indices(2)]
print("\nExtract upper triangular part of the said array:")
print(result)

Sample Output:

Original array:
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]
 [12 13 14]
 [15 16 17]]

Extract upper triangular part of the said array:
[0 1 2 4 5 8]

Extract upper triangular part of the said array:
[0 1 4]

Pictorial Presentation:

NumPy: Extract upper triangular part of a NumPy matrix

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to calculate the sum of all columns of a 2D NumPy array.
Next: Write a NumPy program to get a copy of a matrix with the elements below the k-th diagonal zeroed.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}