/    /  NumPy – Broadcasting

NumPy – Broadcasting:

Operations on Numpy arrays are generally happened on element wise. It means the arrays of same size works better for operations.

But it is also possible to do the operations on the those arrays which are different in size.

How to do this ?

Nothing to do anything by us. Numpy can transform the arrays of different sizes into the same sizes. That kind of formulation or conversion is known as broadcasting in Numpy.

Let us observe the below example:

Creating an array of size 1 column * 4 row

>>> a=np.array([[0],[10],[20],[30]])
>>> a
array([[ 0],
[10],
[20],
[30]])

Creating an array of size 3 column * 1 row

>>> b=np.array([0,1,2])
>>> b
array([0, 1, 2])

Adding the both of them will give us the resultant Array after broadcasting.

>>> a+b
array([[ 0, 1, 2],
[10, 11, 12],
[20, 21, 22],
[30, 31, 32]])

Substracting both of them will give us below result.

>>> a-b
array([[ 0, -1, -2],
[10, 9, 8],
[20, 19, 18],
[30, 29, 28]])

Multiplying the both of them will give us below result.

>>> a*b
array([[ 0, 0, 0],
[ 0, 10, 20],
[ 0, 20, 40],
[ 0, 30, 60]])