在NumPy中建立陣列:對角線及其以下元素為1,其餘元素為0
要建立一個數組,使其對角線及其以下元素為1,其餘元素為0,請在Python NumPy中使用**numpy.tri()**方法。
- 第一個引數是陣列的行數。
- 第二個引數是陣列的列數。
tri()函式返回一個數組,其下三角形填充為1,其他地方為0;換句話說,當j <= i + k時,T[i,j] == 1,否則為0。
步驟
首先,匯入所需的庫。
import numpy as np
現在,使用Python NumPy中的numpy.tri()方法建立一個數組,使其對角線及其以下元素為1,其餘元素為0。
arr = np.tri(4, 4)
顯示我們的陣列。
print("Array...
",arr)
獲取資料型別。
print("
Array datatype...
",arr.dtype)
獲取陣列的維度。
print("
Array Dimensions...
",arr.ndim)
獲取陣列的形狀。
print("
Our Array Shape...
",arr.shape)
獲取陣列的元素個數。
print("
Elements in the Array...
",arr.size)
示例
import numpy as np # To create an array with ones at and below the given diagonal and zeros elsewhere, use the numpy.tri() method in Python Numpy # The 1st parameter is the number of rows in the array # The 2nd parameter is the number of columns in the array arr = np.tri(4, 4) # 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)
輸出
Array... [[1. 0. 0. 0.] [1. 1. 0. 0.] [1. 1. 1. 0.] [1. 1. 1. 1.]] Array datatype... float64 Array Dimensions... 2 Our Array Shape... (4, 4) Elements in the Array... 16
廣告