NumPy中不同形状数组的元素级相减


要对不同形状的参数进行逐元素相减,请在Python NumPy中使用**numpy.subtract()**方法。out是结果存储到的位置。如果提供,它必须具有输入广播到的形状。如果没有提供或为None,则返回一个新分配的数组。元组(仅作为关键字参数可能)的长度必须等于输出的数量。

条件在输入上进行广播。在条件为True的位置,out数组将设置为ufunc结果。在其他位置,out数组将保留其原始值。请注意,如果通过默认的out=None创建未初始化的out数组,则其中条件为False的位置将保持未初始化状态。

NumPy提供了全面的数学函数、随机数生成器、线性代数例程、傅里叶变换等等。它支持各种硬件和计算平台,并且可以很好地与分布式、GPU和稀疏数组库配合使用。

步骤

首先,导入所需的库:

import numpy as np

创建两个不同形状的数组:

arr1 = np.arange(27.0).reshape((3, 3, 3))
arr2 = np.arange(9.0).reshape((3, 3))

显示数组:

print("Array 1...
", arr1) print("
Array 2...
", arr2)

获取数组的类型:

print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype)

获取数组的维度:

Get the dimensions of the Arrays:

获取数组的形状:

print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape)

要对不同形状的参数进行逐元素相减,请在Python NumPy中使用numpy.subtract()方法:

print("
Result (subtract element-wise)...
",np.subtract(arr1, arr2))

示例

import numpy as np

# Create two arrays with different shapes
arr1 = np.arange(27.0).reshape((3, 3, 3))
arr2 = np.arange(9.0).reshape((3, 3))

# 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 with different shapes, use the numpy.subtract() method in Python Numpy print("
Result (subtract element-wise)...
",np.subtract(arr1, arr2))

输出

Array 1...
[[[ 0. 1. 2.]
[ 3. 4. 5.]
[ 6. 7. 8.]]

[[ 9. 10. 11.]
[12. 13. 14.]
[15. 16. 17.]]

[[18. 19. 20.]
[21. 22. 23.]
[24. 25. 26.]]]

Array 2...
[[0. 1. 2.]
[3. 4. 5.]
[6. 7. 8.]]

Our Array 1 type...
float64

Our Array 2 type...
float64

Our Array 1 Dimensions...
3

Our Array 2 Dimensions...
2

Our Array 1 Shape...
(3, 3, 3)

Our Array 2 Shape...
(3, 3)

Result (subtract element-wise)...
[[[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]]

[[ 9. 9. 9.]
[ 9. 9. 9.]
[ 9. 9. 9.]]

[[18. 18. 18.]
[18. 18. 18.]
[18. 18. 18.]]]

更新于:2022年2月7日

1K+ 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.