将输入解释为 NumPy 中的矩阵
要将输入解释为矩阵,请在 Python NumPy 中使用 **numpy.asmatrix()** 方法。与矩阵不同,如果输入已经是矩阵或 ndarray,则 asmatrix 不会创建副本。等效于 matrix(data, copy=False)。
NumPy 提供了全面的数学函数、随机数生成器、线性代数例程、傅里叶变换等等。它支持各种硬件和计算平台,并且与分布式、GPU 和稀疏数组库配合良好。
步骤
首先,导入所需的库 -
import numpy as np
创建一个二维数组 -
arr = np.array([[36, 36, 78, 88], [92, 81, 98, 45], [22, 67, 54, 69 ], [69, 80, 80, 99]])
显示我们的数组 -
print("Array...
",arr)获取数据类型 -
print("
Array datatype...
",arr.dtype)
获取数组的维度 -
print("
Array Dimensions...
",arr.ndim)获取数组的形状 -
print("
Our Array Shape...
",arr.shape)获取数组的元素个数 -
print("
Elements in the Array...
",arr.size)要将输入解释为矩阵,请在 Python NumPy 中使用 numpy.asmatrix() 方法 -
res = np.asmatrix(arr)
print("
Result...
",res)设置一些值 -
arr[0,2] = 99 arr[1,1] = 199 arr[2,1] = 299
显示更新后的矩阵 -
print("
Updated Matrix...
",arr)示例
import numpy as np
# Create a 2d array
arr = np.array([[36, 36, 78, 88], [92, 81, 98, 45], [22, 67, 54, 69], [69, 80, 80, 99]])
# Displaying our array
print("Array...
",arr)
# Get the datatype
print("
Array datatype...
",arr.dtype)
# Get the dimensions of the Array
print("
Array Dimensions...
",arr.ndim)
# Get the shape of the Array
print("
Our Array Shape...
",arr.shape)
# Get the number of elements of the Array
print("
Elements in the Array...
",arr.size)
# To Interpret the input as a matrix, use the numpy.asmatrix() method in Python Numpy
res = np.asmatrix(arr)
print("
Result...
",res)
# Set some values
arr[0,2] = 99
arr[1,1] = 199
arr[2,1] = 299
# Display the updated matrix
print("
Updated Matrix...
",arr)输出
Array... [[36 36 78 88] [92 81 98 45] [22 67 54 69] [69 80 80 99]] Array datatype... int64 Array Dimensions... 2 Our Array Shape... (4, 4) Elements in the Array... 16 Result... [[36 36 78 88] [92 81 98 45] [22 67 54 69] [69 80 80 99]] Updated Matrix... [[ 36 36 99 88] [ 92 199 98 45] [ 22 299 54 69] [ 69 80 80 99]]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP