Skip to content

python numpy ValueError: operands could not be broadcast together with shapes

The ValueError: operands could not be broadcast together with shapes error occurs in NumPy when the shapes of the arrays being operated on are incompatible. Here is an example of code that would raise this error:

Code raising ValueError: operands could not be broadcast together with shapes

python
import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5])

c = a + b

In this example, a has shape (3,) and b has shape (2,). NumPy aligns array dimensions from the right and pads missing dimensions with 1 on the left. Since 3 and 2 are neither equal nor 1, the shapes are incompatible, so the error is raised.

To fix this error, you need to make sure that the shapes of the arrays being operated on are compatible. One way to do this is to reshape the arrays so that they have the same number of dimensions and compatible sizes along each dimension. Another way is to use NumPy functions like np.newaxis, np.expand_dims, np.atleast_1d, np.atleast_2d, etc.

Make sure that the shapes of the arrays being operated on are compatible

python
a = np.array([1, 2, 3])
b = np.array([4, 5])

c = a[:, np.newaxis] + b

This works because b[:, np.newaxis] changes b's shape to (2, 1). NumPy then broadcasts both arrays to a common result shape of (3, 2).

You can also use NumPy's broadcasting functionality by reshaping the arrays to have compatible shapes.

Use NumPy's broadcasting functionality by reshaping the arrays to have compatible shapes

python
a = np.array([1, 2, 3])
b = np.array([4, 5])

c = a + b[:, None]

This works because b[:, None] also changes b's shape to (2, 1). NumPy broadcasts both arrays to a common result shape of (3, 2). Note that np.newaxis and None are interchangeable in NumPy.

For explicit shape management, you can also use np.reshape() to change array dimensions or np.broadcast_shapes() to verify compatibility before performing operations.

Dual-run preview — compare with live Symfony routes.