. Advertisement .
..3..
. Advertisement .
..4..
Little did you know, numpy arrays of various forms cannot be put out together in Python. This means that two 2D arrays including distinctive columns and rows cannot be added together.
That is why it happens the error operands could not be broadcast together with shapes. However, there exists a certain method which you can utilize to achieve that. Scroll down and figure out what it is!
Example Of The Error Operands Could Not Be Broadcast Together With Shapes
Let’s examine a scenario where there are two NumPy arrays. One of the arrays will be reshaped into a 2×2 matrix, and the other into a 2×3 matrix.
import numpy as np
A = np.array([4, 2, 9, 3]).reshape(2, 2)
B = np.array([1, 5, 9, 7, 3, 4]).reshape(2, 3)
print(A)
print(B)
To view the matrices, let’s execute the code, and below is what we will have after having done with the previous process.
[[4 2]
[9 3]]
[[1 5 9]
[7 3 4]]
It’s time for the two matrices to be then multiplied using *.
product = A * B
print(product)
The result will end up with the error we can observe as following:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [10], in <cell line: 1>()
----> 1 product = A * B
2 print(product)
ValueError: operands could not be broadcast together with shapes (2,2) (2,3)
As a matter of fact, the arithmetic operator * only functions if the smaller array can be broadcast to the bigger array size or the arrays are of equal shape. Since we are employing that operation, it triggers such an error to happen.
The Error Operands Could Not Be Broadcast Together With Shapes: Solution
As you have grasped, the two 2D arrays must first ensure having the same forms so the error can be prevented. The only way it can be possible is to employ the reshaping functionalities. The 2nd array is being reshaped in the following code to match the first array’s shapes.
You can combine these two arrays as soon as the shapes do not any more differ from each other.
Running the 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]])
#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]]
The Bottom Line
The problem is not at all tricky to tackle, isn’t it? Now that you have known how to solve the error operands could not be broadcast together with shapes, it’s time to pave your way and get your coding done successfully.
Hopefully, this article can be of great help to you somehow. See then!
Leave a comment