返回陣列的下三角,並在 NumPy 中將對角線以上元素設定為零


要返回陣列的下三角,請在 Python NumPy 中使用 **numpy.tril()** 方法 -

  • 第一個引數是輸入陣列
  • 第二個引數是“k”,即要將元素歸零的對角線以上。
  • k = 0(預設值)為主對角線,k < 0 在其下方,k > 0 在其上方。

該函式返回一個數組的副本,其中 k 對角線以上的元素歸零。對於 ndim 超過 2 的陣列,tril 將應用於最後兩個軸。

步驟

首先,匯入所需的庫 -

import numpy as np

建立一個二維陣列 -

arr = np.array([[36, 36, 78, 88], [92, 81, 98, 45], [22, 67, 54, 69 ], [69, 80, 80, 99]])

顯示我們的陣列 -

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)

使用 Python NumPy 中的 numpy.tril() 方法返回陣列的下三角。第二個引數是“k”,即要將元素歸零的對角線以上。這裡,k = 0(預設值)為主對角線,k < 0 在其下方,k > 0 在其上方 -

print("
Result...
",np.tril(arr, k = 1))

示例

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 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("
Result...
",np.tril(arr, k = 1))

輸出

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]]

更新於: 2022年2月16日

294 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.