使用深度為 2 的列表在 Numpy 中構建塊矩陣
若要構建矩陣塊,請在 Python Numpy 中使用 numpy.block() 方法。在此,我們將根據深度為 2 的列表構建塊矩陣。最內層列表中的塊沿最後一個維(-1)連線,然後沿倒數第二個維(-2)連線,如此類推,直到到達最外層的列表。
塊可以是任何維度的,但不會使用常規規則進行廣播。相反,會插入值為 1 的前置軸,使所有塊的 block.ndim 相同。這主要用於使用標量,這意味著 np.block([v, 1]) 之類的程式碼有效,其中 v.ndim == 1。
步驟
首先,匯入所需庫 −
import numpy as np
使用 array() 方法建立兩個 numpy 陣列。我們插入了 int 型別的元素 −
arr1 = np.array([49, 76, 61, 82, 69, 29]) arr2 = np.array([40, 60, 89, 55, 32, 98])
顯示陣列 −
print("Array 1...
", arr1) print("
Array 2...
", arr2)
獲取陣列型別 −
print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype)
獲取陣列的維度 −
print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim)
獲取陣列的形狀 −
print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape)
要在 Python Numpy 中構建矩陣塊,請使用 numpy.block() 方法 −
print("
Result...
",np.block([[arr1], [arr2]]))
示例
import numpy as np # Creating two numpy arrays using the array() method # We have inserted elements of int type arr1 = np.array([49, 76, 61, 82, 69, 29]) arr2 = np.array([40, 60, 89, 55, 32, 98]) # Display the arrays print("Array 1...
", arr1) print("
Array 2...
", arr2) # Get the type of the arrays print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype) # Get the dimensions of the Arrays print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim) # Get the shape of the Arrays print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape) # To build a block of matrix, use the numpy.block() method in Python Numpy print("
Result...
",np.block([[arr1], [arr2]]))
輸出
Array 1... [49 76 61 82 69 29] Array 2... [40 60 89 55 32 98] Our Array 1 type... int64 Our Array 2 type... int64 Our Array 1 Dimensions... 1 Our Array 2 Dimensions... 1 Our Array 1 Shape... (6,) Our Array 2 Shape... (6,) Result... [[49 76 61 82 69 29] [40 60 89 55 32 98]]
廣告