在 Numpy 中返回陣列的上三角
若要返回陣列的上三角,請在 Python NumPy 中使用 **numpy.triu()** 方法。第 1 個引數是輸入陣列。該函式會返回一個副本,其 kth 對角線以下的元素清零。對於維度超過 2 的陣列,triu 會應用於最後兩個軸。
步驟
首先,匯入所需的庫 −
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.triu() 方法。第 1 個引數是輸入陣列 −
print("
Result...
",np.triu(arr))
示例
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))輸出
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]]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C ++
C#
MongoDB
MySQL
Javascript
PHP