HOWTO · Python

修复 Python 中操作数不能与形状一起广播的错误

如何修复操作数无法与 Python 中的形状错误一起广播

在 Python 中,不同形状的 numpy 数组不能一起广播。这意味着你不能添加两个具有不同行和列的二维数组。

但是有一种方法可以做到这一点。看一看。

修复 Python 中的 operands could not be broadcast together with shapes 错误

你不能将两个具有不同形状的二维数组相加或相乘。看看下面的代码。

import numpy as np

# Addition Example

# 2d array with shape 2 rows and 3 columns
array_1 = np.array([[1, 1, 1], [1, 1, 1]])
# 2d array with shape 3 rows and 2 columns
array_2 = np.array([[1, 1], [1, 1], [1, 1]])
# Addition applying on the arrays
array_Addition = array_1 + array_2

如你所见,有两个具有不同形状的二维数组。

第一个数组有两行三列,第二个数组是三行两列。添加它们将给出此错误操作数无法与形状一起广播

它的工作原理与在数学中添加两个矩阵相同。

第一个数组的第一个元素与第二个数组的第一个元素相加,第二个元素将与第二个元素相加。因此,如果形状不匹配,则会出错。

因此,我们需要使用重塑功能使两个二维数组具有相同的形状。在下面的代码中,我们将根据第一个数组的形状重塑第二个数组。

一旦形状相同,你可以添加两个数组。

import numpy as np

# Addition Example

# 2d array with shape 2 rows and 3 columns
array_1 = np.array([[1, 1, 1], [1, 1, 1]])
# 2d array with shape 3 rows and 2 columns
array_2 = np.array([[1, 1], [1, 1], [1, 1]])

# changing the shape of array_2 according to the Array_1 or Array_1 according to Array_2
array_2 = array_2.reshape((2, 3))

# again Addition applying on the arrays
array_Addition = array_1 + array_2

print(array_Addition)

输出:

[[2 2 2]
 [2 2 2]]