使用Numpy中的广播计算两个向量相加


要生成模拟广播的对象,请使用 Python Numpy 中的 **numpy.broadcast()** 方法。如果上述规则生成的结果有效,且以下条件之一为真,则称一套数组可广播 −

  • 数组的形状完全相同。
  • 数组的维度数相同,且每个维度的长度要么是公共长度,要么是 1。
  • 维度过少的数组可以将长度为 1 的维度前置到它的形状, ώ 使得上述所述性质为真。

步骤

首先,导入必需的库 −

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)

要生成模拟广播的对象,请使用 numpy.broadcast () 方法 −

x = np.broadcast(arr1, arr2)
res = np.empty(x.shape)
res.flat = [i+j for (i,j) in x]
print("
Result...
",res)

示例

import numpy as np

# Create two arrays
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 produce an object that mimics broadcasting, use the numpy.add() method in Python Numpy x = np.broadcast(arr1, arr2) res = np.empty(x.shape) res.flat = [i+j for (i,j) in x] print("
Result...
",res)

输出

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...
[[12. 24. 36.]
[53. 65. 91.]]

更新时间: 2022 年 2 月 17 日

250 次浏览

开始您的 职业

完成课程获得认证

开始
广告