NumPy Tutorial NumPy Statistics NumPy References

NumPy - Broadcasting



The term 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.

If the arithmetic operations are performed with arrays of exact same shape, then the operations are done element-to-element, as shown in the example below:

Example:

import numpy as np
Arr1 = np.array([1, 2, 3, 4, 5])
Arr2 = np.array([10, 20, 30, 40, 50])
Arr3 = Arr1 * Arr2

print(Arr3)

The output of the above code will be:

[ 10  40  90 160 250]

When the shape of two arrays are not same, then element-to-element operation is not possible. However, numpy provides capability to perform arithmetic operations in such cases through broadcasting. This leads to certain constraints.

Broadcasting Rules

Broadcasting two arrays follows below mentioned rules:

  • Smaller dimension array is prepended with '1' in its shape.
  • Size in each dimension of the output shape is maximum of the input sizes in that dimension.
  • An input can be used in the calculation if its size in a particular dimension matches the output size or its value is exactly 1.
  • If an input has a dimension size of 1, the first data entry in that dimension is used for all calculations along that dimension.

Broadcasting can be applied to the arrays if the following rules are satisfied.

  • Arrays have exactly the same shape.
  • Arrays have the same number of dimensions, and the length of each dimension is either a common length or 1.
  • Array having too few dimensions can have its shape prepended with a dimension of length 1 in its shape.

Example:

In the example below, array Arr2 is broadcast across the array Arr1 while performing the addition operation.

import numpy as np
Arr1 = np.array([[0, 0, 0, 0],
                 [10, 10, 10, 10],
                 [20, 20, 20, 20]])
Arr2 = np.array([3, 5, 7, 8])
Arr3 = Arr1 + Arr2

print("Arr1:")
print(Arr1)

print("\nArr2:")
print(Arr2)

print("\nArr3:")
print(Arr3)

The output of the above code will be:

Arr1:
[[ 0  0  0  0]
 [10 10 10 10]
 [20 20 20 20]]

Arr2:
[3 5 7 8]

Arr3:
[[ 3  5  7  8]
 [13 15 17 18]
 [23 25 27 28]]
Array Broadcasting