What is the numpy.tril() function in Python?
Overview
The tril() function in Python is used to return a lower triangle of an array.
Syntax
array.tril(m, k=0)
array is the name of the array to tril.
Parameters
The tril() function takes the following parameter values:
m: Represents thearray_likeobject or the input array.k: Represents the diagonal above or below the main diagonal.K<0is below the main diagonal andk>0is above the main diagonal.
Return value
The tril() function returns a lower triangle of the same shape and data type as the array m passed to it.
Example
import numpy as np# creating an arraymyarray = np.arange(9).reshape((3,3))# implementing the tril() functiontrilarray = np.tril(myarray, k=0)print("Original array is:", myarray)print("Manipulated array is:",trilarray)
Explanation
In the above code:
- Line 1: We import the
numpylibrary. - Line 4: We create an array
myarraythat contains9values with a dimension of3 by 3(3rows and3columns) using thearange()function. - Line 7: We implement the
tril()function on the arraymyarrayusing the main diagonalk = 0. The result is assigned to a new variabletrilarray. - Line 9: We print the array
myarray. - Line 10: We print the new array
trilarray.