
Read Time:185 Minute, 21 Second
NumPy Array Broadcasting¶
Broadcasting is the name given to the method that NumPy uses to allow array arithmetic between arrays with a different shape or size. Broadcasting has the following 1imitations:- at least one array dimension is equal to 1.
- The number of columns in the each of arrays must be equal.
Scalar and One-Dimensional Array¶
After the broadcasting, Scalar b will be array([2,2,2]).In [26]:
from numpy import array
a = array([1,2,3])
b = 2
c = a + b
print(c)
Scalar and Two-Dimensional Array¶
After the broadcasting, Scalar b will be array([[5,5,5], [5,5,5]]).In [27]:
from numpy import array
a = array([[1,2,3],
[4,5,6]])
b = 5
c = a + b
print(c)
One-Dimensional and Three-Dimensional Arrays¶
After the broadcasting, array b will be array([[7,8,9], [7,8,9],[7,8,9]) .In [40]:
from numpy import array
a = array([[1,2,3],
[4,5,6],
[10,11,12]])
print(a.shape)
b = array([7, 8, 9])
print(b.shape)
c = a + b
print(c)
Limitations of Broadcasting¶
The broadcasting fails; array a and array b have the different number of columns.In [29]:
from numpy import array
a = array([[1,2],
[4,5],
[7,8]])
print(a.shape)
b = array([7, 8, 9])
print(b.shape)
c = a + b
print(c)
The broadcasting fails; array a and array b have the different number of columns.
In [34]:
from numpy import array
a = array([[1,2,3],
[4,5,6],
[7,8,9]])
print(a.shape)
b = array([7,8])
print(b.shape)
c = a + b
print(c)
The broadcasting fails; none of array dimensions are equal to 1, althought, array a and array b have the same number of columns.
In [31]:
from numpy import array
a = array([[1,2,3],
[4,5,6],
[7,8,9]])
print(a.shape)
b = array([[10,11,12],
[13,14,15]])
print(b.shape)
c = a + b
print(c)
In [ ]: