Last updated: Apr 11, 2024
Reading time·5 min
The Python "ValueError: shape mismatch: objects cannot be broadcast to a single shape" occurs when the two inputs you've supplied have incompatible shapes.
To solve the error, make sure that the x
and y
inputs have the same or
compatible shapes.
Here is an example of how the error occurs when using matplotlib
.
import matplotlib.pyplot as plt x = ['bobby', 'hadz'] y = [2, 4, 6] # ⛔️ ValueError: shape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 0 with shape (2,) and arg 1 with shape (3,). plt.bar(x, y) # ⛔️ ValueError: ... plt.barh(x, y) plt.show()
Notice that the shapes of the x
and y
lists are not the same and are not
compatible.
The first list has 2 elements and the second has 3.
The matplotlib.pyplot.bar() method makes a bar plot.
The x
parameter is used to specify the x
coordinates of the bars.
The y
parameter is used to specify the height(s) of the bars.
For example, if I make both lists of 3 elements each, everything works as expected.
import matplotlib.pyplot as plt x = ['bobby', 'hadz', 'com'] y = [2, 4, 6] plt.bar(x, y) plt.show()
If you need to check the length of a one-dimensional list, use the len()
function.
x = ['bobby', 'hadz', 'com'] print(len(x)) # 👉️ 3
If you need to get the length of a 2D array, check out the following article.
If your x
and y
parameters are not the same (or compatible) shapes, use
list slicing.
import matplotlib.pyplot as plt x = ['bobby', 'hadz'] y = [2, 4, 6] plt.bar(x, y[:len(x)]) plt.show()
The syntax for list slicing is my_list[start:stop:step]
.
start
index is inclusive and the stop
index is exclusive (up to, but not including).We used the len()
function when specifying the stop
index.
The x
list only has 2 items, so we used len(x)
to specify a stop
index of
2
and select only the first 2 elements of the y
list.
Broadcasting describes how NumPy treats arrays with different shapes during arithmetic operations.
The smaller array is "broadcast" across the larger array so that they have compatible shapes.
You will usually do NumPy operations on a pair of arrays, element-wise.
In the simplest case, the two arrays will have the same shape.
import numpy as np x = np.array([1, 2, 3]) y = np.array([2, 2, 2]) print(x * y) # 👉️ [2 4 6]
The arrays have 3 elements each, so we multiplied them element-wise without running into any issues.
However, if the two arrays have incompatible shapes, the ValueError
is raised.
import numpy as np x = np.array([1, 2, 3]) y = np.array([2, 2]) # ⛔️ ValueError: operands could not be broadcast together with shapes (3,) (2,) print(x * y)
The first array has 3 elements and the second has only 2.
Their shapes are incompatible, so they cannot be broadcast together.
You can also broadcast an array and a scalar value.
import numpy as np x = np.array([1, 2, 3]) y = 2 print(x * y) # 👉️ [2 4 6] arr = np.broadcast_arrays(x, y) print(arr) # 👉️ [array([1, 2, 3]), array([2, 2, 2])]
NumPy knows that we are trying to multiply each element of the x
array by y
.
This is equivalent to setting y
to an array containing 3 elements with a value
of 2
- np.array([2, 2, 2])
.
2
into an array that contains 3 elements with a value of 2
.y = 2 # becomes the following array y = np.array([2, 2, 2])
When you do arithmetic operations with a pair of arrays, NumPy compares their shapes element-wise.
It starts with the rightmost dimension and works its way left.
Two dimensions are compatible when:
1
.If neither of the 2 conditions is met, a ValueError
is raised.
You can use the shape
attribute if you need to print the shape of an array.
import numpy as np x = np.array([1, 2, 3]) print(x.shape) # 👉️ (3,) y = np.array([2, 2]) print(y.shape) # 👉️ (2,)
The numpy.shape attribute returns the shape of an array.
The returned tuple contains the lengths of the array's dimensions.
Note that the arrays don't have to have the same number of dimensions.
import numpy as np x = np.array([1, 2, 3]) print(x.shape) # 👉️ (3,) y = np.array([[2], [2]]) print(y.shape) # 👉️ (2, 1) # [[2 4 6] # [2 4 6]] print(x * y)
The first array is one-dimensional and the second array is two-dimensional.
The returned array will have the same number of dimensions as the supplied array that has the greatest number of dimensions.
Missing dimensions are assumed to have a size of 1
.
As previously noted, arrays with a size of 1
are stretched to match the other
array.
You can learn more about the related topics by checking out the following tutorials: