What Is Numpy Broadcasting ?
Table Of Contents:
- What Is Broadcasting ?
- Examples Of Broadcasting.
(1) What Is Broadcasting ?
- The term broadcasting describes how NumPy treats arrays with different shapes during arithmetic operations.
- Subject to certain constraints, the smaller array is “broadcast” across the larger array so that they have compatible shapes.
(2) Examples Of Broadcasting ?
Example-1:
import numpy as np
data = np.array([1.0, 2.0])
data * 1.6
Output:
array([1.6, 3.2])
Example-2:
a = np.array([[ 0.0, 0.0, 0.0],
[10.0, 10.0, 10.0],
[20.0, 20.0, 20.0],
[30.0, 30.0, 30.0]])
b = np.array([1.0, 2.0, 3.0])
a + b
Output:
array([[ 1., 2., 3.],
[11., 12., 13.],
[21., 22., 23.],
[31., 32., 33.]])
Example-3:
a = np.array([[ 0.0, 0.0, 0.0],
[10.0, 10.0, 10.0],
[20.0, 20.0, 20.0],
[30.0, 30.0, 30.0]])
b = np.array([1.0, 2.0, 3.0, 4.0])
a + b
Output:
ValueError Traceback (most recent call last)
Input In [39], in <cell line: 6>()
1 a = np.array([[ 0.0, 0.0, 0.0],
2 [10.0, 10.0, 10.0],
3 [20.0, 20.0, 20.0],
4 [30.0, 30.0, 30.0]])
5 b = np.array([1.0, 2.0, 3.0, 4.0])
----> 6 a + b
ValueError: operands could not be broadcast together with shapes (4,3) (4,)