在 NumPy 中按元素相减并以不同类型显示结果
要按元素相减参数,请在 Python NumPy 中使用 **numpy.subtract()** 方法。输出使用“**dtype**”参数设置为“**float**”。
out 是存储结果的位置。如果提供,它必须具有输入广播到的形状。如果未提供或为 None,则返回一个新分配的数组。元组(仅可能作为关键字参数)的长度必须等于输出的数量。
条件在输入上广播。在条件为 True 的位置,out 数组将设置为 ufunc 结果。在其他地方,out 数组将保留其原始值。请注意,如果通过默认的 out=None 创建了一个未初始化的 out 数组,则其中条件为 False 的位置将保持未初始化。
NumPy 提供了全面的数学函数、随机数生成器、线性代数例程、傅里叶变换等等。它支持广泛的硬件和计算平台,并且可以很好地与分布式、GPU 和稀疏数组库配合使用。
步骤
首先,导入所需的库 -
import numpy as np
创建两个具有整数元素的二维数组 -
arr1 = np.array([[5, 10, 15], [25, 30, 35]]) arr2 = np.array([[7, 14, 21], [28, 35, 56]])
显示数组 -
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.subtract() 方法。输出使用“dtype”参数设置为“float”
print("
Result (subtract element-wise)...
",np.add(arr1, arr2, dtype = 'float'))
示例
import numpy as np
# Create two 2D arrays with int elements
arr1 = np.array([[5, 10, 15], [25, 30, 35]])
arr2 = np.array([[7, 14, 21], [28, 35, 56]])
# 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 subtract arguments element-wise, use the numpy.subtract() method in Python Numpy
# The output is set "float" using the "dtype" parameter
print("
Result (subtract element-wise)...
",np.add(arr1, arr2, dtype = 'float'))输出
Array 1... [[ 5 10 15] [25 30 35]] Array 2... [[ 7 14 21] [28 35 56]] Our Array 1 type... int64 Our Array 2 type... int64 Our Array 1 Dimensions... 2 Our Array 2 Dimensions... 2 Our Array 1 Shape... (2, 3) Our Array 2 Shape... (2, 3) Result (subtract element-wise)... [[12. 24. 36.] [53. 65. 91.]]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP