Arithmetic operations with NumPy are usually done element-wise. For instance, when we add two arrays, the elements in the same positions are added.
a = np.array([1,2,3,4])
b = np.array([1,1,1,1])a + b
array([2, 3, 4, 5])
Since the operations are done element-wise, the arrays must have the same shape. Broadcasting allows for some flexibility on this condition so arithmetic operations can be done on arrays with different shapes.
There are still some rules that must be satisfied. We cannot just broadcast any arrays. In the following examples, we will explore these rules and how broadcasting occurs.
The simplest form of broadcasting occurs when we an array and a scalar are added.
a = np.array([1,2,3,4])
b = 1a + b
array([2, 3, 4, 5])
The addition operation is done as if b was an array with 4 integers of 1.
The illustrated stretching in the figure is only conceptual. NumPy does not actually make copies of the scalar to match the size of the array. Instead, the original scalar value is used in the addition. Thus, broadcasting operations are highly efficient in terms of memory and computation.
We can also add a scalar to a higher dimensional array. In that case, broadcasting occurs in all axes. In the following example, we have a two-dimensional array with a shape of (3,4). The scalar is added to all the elements of the array.
A = np.random.randint(5, size=(3, 4))
B = 2print(A)
print("--------")
print(A + B)[[0 1 0 0]
[0 2 4 3]
[0 1 2 1]]
--------
[[2 3 2 2]
[2 4 6 5]
[2 3 4 3]]
The broadcasting in this example occurs as follows: