w3resource

NumPy: Set zero to lower triangles along the last two axes of a three-dimensional of a given array

NumPy: Array Object Exercise-173 with Solution

Write a NumPy program to set zero to lower triangles along the last two axes of a three-dimensional of a given array.

Sample Solution:

Python Code:

import numpy as np
arra=np.ones((1,8,8))
print("Original array:")
print(arra)
result = np.triu(arra, k=1)
print("\nResult:")
print(result)

Sample Output:

Original array:
[[[1. 1. 1. 1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1. 1. 1. 1.]]]

Result:
[[[0. 1. 1. 1. 1. 1. 1. 1.]
  [0. 0. 1. 1. 1. 1. 1. 1.]
  [0. 0. 0. 1. 1. 1. 1. 1.]
  [0. 0. 0. 0. 1. 1. 1. 1.]
  [0. 0. 0. 0. 0. 1. 1. 1.]
  [0. 0. 0. 0. 0. 0. 1. 1.]
  [0. 0. 0. 0. 0. 0. 0. 1.]
  [0. 0. 0. 0. 0. 0. 0. 0.]]]

Pictorial Presentation:

NumPy: Set zero to lower triangles along the last two axes of a three-dimensional of a given array

Python Code Editor:

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

Previous: Write a NumPy program to find and store non-zero unique rows in an array after comparing each row with other row in a given matrix.
Next: Write a NumPy program to get the number of items, array dimensions, number of array dimensions and the memory size of each element of a given array.

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}