用深度為1的列表建立NumPy中的塊矩陣
要構建一個矩陣塊,請在Python Numpy中使用numpy.block()方法。這裡,我們將從深度為一的列表中構建。內部列表中的塊沿著最後一個維度(-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, 99]))
示例
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, 99]))輸出
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 99]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP