Return the Lower triangle of an array and set the diagonal above which to zero elements in Numpy

NumpyServer Side ProgrammingProgramming

Python Data Science basics with Numpy, Pandas and Matplotlib

Most Popular

63 Lectures 6 hours

Data Analysis using NumPy and Pandas

19 Lectures 8 hours

Numpy with Python

Most Popular

12 Lectures 3 hours

To return the lower triangle of an array, use the numpy.tril() method in Python Numpy −

• The 1st parameter is the input array
• The 2nd parameter is the 'k' i.e. the diagonal above which to zero elements.
• k = 0 (the default) is the main diagonal, k <0 is below it and k > 0 is above.

The function returns a copy of an array with elements above the k-th diagonal zeroed. For arrays with ndim exceeding 2, tril 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...\n",arr)

Get the datatype −

print("\nArray datatype...\n",arr.dtype)

Get the dimensions of the Array −

print("\nArray Dimensions...\n",arr.ndim)

Get the shape of the Array −

print("\nOur Array Shape...\n",arr.shape)

Get the number of elements of the Array −

print("\nElements in the Array...\n",arr.size)

Return the lower triangle of an array using the numpy.tril() method in Python Numpy. The 2nd parameter is the 'k' i.e. the diagonal above which to zero elements. Here, k = 0 (the default) is the main diagonal, k < 0 is below it and k > 0 is above −

print("\nResult...\n",np.tril(arr, k = 1))


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...\n",arr)

# Get the datatype
print("\nArray datatype...\n",arr.dtype)

# Get the dimensions of the Array
print("\nArray Dimensions...\n",arr.ndim)

# Get the shape of the Array
print("\nOur Array Shape...\n",arr.shape)

# Get the number of elements of the Array
print("\nElements in the Array...\n",arr.size)

# To return the lower triangle of an array, use the numpy.tril() method in Python Numpy
# The 1st parameter is the input array
# The 2nd parameter is the 'k' i.e. the diagonal above which to zero elements.
# k = 0 (the default) is the main diagonal, k < 0 is below it and k > 0 is above.' array
print("\nResult...\n",np.tril(arr, k = 1))

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 0 0]
[92 81 98 0]
[22 67 54 69]
[69 80 80 99]]
Updated on 16-Feb-2022 10:53:06