使用深度为 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]]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
JavaScript
PHP