NumPy Broadcast(Broadcast)
Broadcast is the way numpy performs numerical calculations on arrays of different shapes; arithmetic operations on arrays are usually performed on the corresponding elements.
If two arrays a and b have the same shape, i.e. satisfying a.shape == b.shape, then the result of a*b is the multiplication of the corresponding positions of arrays a and b. This requires the same number of dimensions and the same length in each dimension.
Example
import
numpy
as
np
a
=
np
.
array
(
[
1
,
2
,
3
,
4
]
)
b
=
np
.
array
(
[
10
,
20
,
30
,
40
]
)
c
=
a
b
(
c
)
The output is:
[ 10 40 90 160]
When the two arrays in an operation have different shapes, numpy automatically triggers the broadcasting mechanism. For example:
Example
import
numpy
as
np
a
=
np
.
array
(
[
[
0
,
0
,
0
]
,
[
10
,
10
,
10
]
,
[
20
,
20
,
20
]
,
[
30
,
30
,
30
]
]
)
b
=
np
.
array
(
[
0
,
1
,
2
]
)
(
a
b
)
The output is:
[[ 0 1 2]
[10 11 12]
[20 21 22]
[30 31 32]]
The following picture shows how array b is made compatible with array a through broadcasting.

Adding a 4x3 two-dimensional array to a one-dimensional array of length 3 is equivalent to repeating array b 4 times in two dimensions before the operation:
Example
import
numpy
as
np
a
=
np
.
array
(
[
[
0
,
0
,
0
]
,
[
10
,
10
,
10
]
,
[
20
,
20
,
20
]
,
[
30
,
30
,
30
]
]
)
b
=
np
.
array
(
[
1
,
2
,
3
]
)
bb
=
np
.
tile
(
b
,
(
4
,
1
)
)
Repeat each dimension of b
(
a
bb
)
The output is:
[[ 1 2 3]
[11 12 13]
[21 22 23]
[31 32 33]]
Broadcasting rules:
- Align all input arrays to the one with the longest shape, padding the deficient parts of the shape by adding 1 at the front.
- The shape of the output array is the maximum value along each dimension of the input array shapes.
- If a dimension of an input array has the same length as the corresponding dimension of the output array, or its length is 1, then this array can be used for the calculation; otherwise an error occurs.
- When the length of a dimension of an input array is 1, the first set of values along this dimension is used for operations along that dimension.
**Simple understanding:** For two arrays, compare each of their dimensions separately (if one array does not have the current dimension, ignore it), satisfying:
- The arrays have the same shape.
- The values of the current dimension are equal.
- One of the values of the current dimension is 1.
If the conditions are not met, raise "ValueError: frames are not aligned" exception.