用深度为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