在 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.eye(2) * 2 arr2 = np.eye(3) * 2
显示数组 -
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,np.zeros((2, 3))], [np.ones((3, 2)), arr2]]))
代码示例
import numpy as np # Creating two numpy arrays using the array() method # We have inserted elements of int type arr1 = np.eye(2) * 2 arr2 = np.eye(3) * 2 # 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,np.zeros((2, 3))], [np.ones((3, 2)), arr2]]))
输出
Array 1... [[2. 0.] [0. 2.]] Array 2... [[2. 0. 0.] [0. 2. 0.] [0. 0. 2.]] Our Array 1 type... float64 Our Array 2 type... float64 Our Array 1 Dimensions... 2 Our Array 2 Dimensions... 2 Our Array 1 Shape... (2, 2) Our Array 2 Shape... (3, 3) Result... [[2. 0. 0. 0. 0.] [0. 2. 0. 0. 0.] [1. 1. 2. 0. 0.] [1. 1. 0. 2. 0.] [1. 1. 0. 0. 2.]]
广告