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]]