- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Return the Upper triangle of an array in Numpy
To return the upper triangle of an array, use the numpy.triu() method in Python Numpy. The 1st parameter is the input array. The function returns a copy of an array with the elements below the kth diagonal zeroed. For arrays with ndim exceeding 2, triu will apply to the final two axes.
Steps
At first, import the required library −
import numpy as np
Create a 2d array −
arr = np.array([[36, 36, 78, 88], [92, 81, 98, 45], [22, 67, 54, 69 ], [69, 80, 80, 99]])
Displaying our array −
print("Array...
",arr)
Get the datatype −
print("
Array datatype...
",arr.dtype)
Get the dimensions of the Array −
print("
Array Dimensions...
",arr.ndim)
Get the shape of the Array −
print("
Our Array Shape...
",arr.shape)
Get the number of elements of the Array −
print("
Elements in the Array...
",arr.size)
To return the upper triangle of an array, use the numpy.triu() method in Python Numpy. The 1st parameter is the input array −
print("
Result...
",np.triu(arr))
Example
import numpy as np # Create a 2d array arr = np.array([[36, 36, 78, 88], [92, 81, 98, 45], [22, 67, 54, 69], [69, 80, 80, 99]]) # Displaying our array print("Array...
",arr) # Get the datatype print("
Array datatype...
",arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Elements in the Array...
",arr.size) # To return the upper triangle of an array, use the numpy.triu() method in Python Numpy # The 1st parameter is the input array print("
Result...
",np.triu(arr))
Output
Array... [[36 36 78 88] [92 81 98 45] [22 67 54 69] [69 80 80 99]] Array datatype... int64 Array Dimensions... 2 Our Array Shape... (4, 4) Elements in the Array... 16 Result... [[36 36 78 88] [ 0 81 98 45] [ 0 0 54 69] [ 0 0 0 99]]
Advertisements