How to Fix Operands Could Not Be Broadcast Together With Shapes Error in Python

Haider Ali Feb 02, 2024
How to Fix Operands Could Not Be Broadcast Together With Shapes Error in Python

In Python, numpy arrays with different shapes cannot be broadcast together. It means you cannot add two 2D arrays with different rows and columns.

But there is a way through which you can do that. Take a look.

Fix operands could not be broadcast together with shapes Error in Python

You can not add or multiply two 2D arrays with different shapes. Take a look at the following code.

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

As you can see, there are two 2D arrays with different shapes.

The first array has two rows and three columns, and the second array is three rows and two columns. Adding them will give this error operands could not be broadcast together with shapes.

It works the same as adding two matrices in mathematics.

The first element of the first array is added with the first element of the second array, and the second element will be added with the second one. So, if the shapes aren’t matched, it will give an error.

Therefore, we need to use the reshaping functionalities to have the same shapes for the two 2D arrays. In the following code, we are reshaping the second array according to the shapes of the first.

Once the shapes are the same, you can add the two arrays.

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)

Output:

[[2 2 2]
 [2 2 2]]
Author: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

Related Article - Python Error

Related Article - Python NumPy