When adding two NumPy arrays, the shapes of the arrays must be compatible. This means that the arrays must have the same shape, or at least one of the dimensions must be of size 1 (a singleton dimension) so that it can be broadcast to the shape of the other array.
Adding Arrays with the Same Shape
If the arrays have the same shape, you can simply use the +
operator to perform element-wise addition:
import numpy as np
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
result = arr1 + arr2
print(result)
## Output: [[ 6 8]
## [10 12]]
Adding Arrays with Different Shapes (Broadcasting)
If the arrays have different shapes, NumPy will attempt to broadcast the arrays to a common shape before performing the addition. Broadcasting is a powerful feature that allows you to perform operations on arrays of different shapes.
import numpy as np
## Broadcasting a 1D array with a 2D array
arr1d = np.array([1, 2, 3])
arr2d = np.array([[4, 5, 6], [7, 8, 9]])
result = arr1d + arr2d
print(result)
## Output: [[ 5 7 9]
## [ 8 10 12]]
## Broadcasting a scalar with a 2D array
scalar = 10
arr2d = np.array([[1, 2, 3], [4, 5, 6]])
result = scalar + arr2d
print(result)
## Output: [[11 12 13]
## [14 15 16]]
In the examples above, NumPy automatically broadcasts the 1D array and the scalar to match the shape of the 2D array, allowing the addition to be performed.
Handling Incompatible Shapes
If the arrays have shapes that cannot be broadcast to a common shape, NumPy will raise a ValueError
exception:
import numpy as np
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6, 7], [8, 9, 10]])
result = arr1 + arr2
## ValueError: operands could not be broadcast together with shapes (2,2) (2,3)
In such cases, you may need to reshape or transpose one or both of the arrays to make their shapes compatible before performing the addition.