In this article we will see Python code to resolve valueerror: shape mismatch: objects cannot be broadcast to a single shape. This error occurs when one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar).
When you do arithmetic operations like addition, multiplication over variables of different shape then this error occurs.
Code Example
Error Code – Let’s first replicate the error –
import matplotlib.pyplot as plt import numpy as np x = np.arange(10) y = np.arange(11) plt.bar(x, y)
This code will generate valueerror: shape mismatch: objects cannot be broadcast to a single shape. Because (x,y) co-ordinates are always in pairs and if there are more y than x, then how will you plot them? Same issue happens with different libraries and they throw error.
The error could also occur in SciPy Pearson correlation coefficient function pearsonr(x,y)
. Both x and y needs to have same shape. The below code will throw error –
from scipy import stats res = stats.pearsonr([1, 2, 3, 4], [10, 9, 2.5, 6, 4]) print(res)
Error –
Traceback (most recent call last): File "pearsonr.py", line 2, in <module> res = stats.pearsonr([1, 2, 3, 4], [10, 9, 2.5, 6, 4]) File "/usr/lib/python3.6/site-packages/scipy/stats/stats.py", line 3001, in pearsonr r_num = np.add.reduce(xm * ym) ValueError: operands could not be broadcast together with shapes (4,) (5,)
Solution
Keep the shape of variables similar.
import matplotlib.pyplot as plt import numpy as np x = np.arange(11) y = np.arange(11) plt.bar(x, y)
Now we set both (x,y) co-ordinates of same shape. So, it will work fine.
from scipy import stats res = stats.pearsonr([1, 2, 3, 4, 5], [10, 9, 2.5, 6, 4]) print(res)
Here we set both arrays of same shape in pearsonr
method. Output will be –
(-0.7426106572325057, 0.15055580885344547)