Broadcasting With Numpy Arrays

Broadcasting is the mechanism that allows numpy to work with different shapes of arrays while performing arithmetic operation. Arithmetic operation are done usually done on corresponding elements i.e. If two arrays are of exactly the same shape, then these operations are smoothly performed.

In NumPy, we can perform such operations where the array of different shapes are involved.

Therefore, Suppose we have two arrays one is smaller array and larger array so, in this method we broadcast smaller array across the larger array because they have compatible shapes.

Broadcasting leads to inefficient use of memory that slow down the computation.

Broadcasting Rules

There are some rules which we need to follow for performing broadcasting.

Broadcasting is only possible if the following cases are satisfied:

  • Array having smaller dimension can be appended with '1' in its shape.
  • The size of each output dimension should be maximum to that of input size dimension.
  • If the input array has dimension size 1 then the first entry in that dimension is used for the calculation along that dimension.

Here are some rules which we also need to satisfy for broadcasting:

  • All the input array should have the same shape.
  • Arrays should have same dimension and length, and the length of each dimension is either a common length or 1.
  • Arrays with less dimension can be pre-appended with '1' in its shape. 


import numpy as np

x = np.array([1,2,3,4,5,6])
y = np.array([10,20,30,40,50,60,70])

z = x+y


ValueError: operands could not be broadcast together with shapes (7,) (6,)

Here we will get value error because we can see that the shapes of these two array are not same so we cannot find the sum of these two arrays.

But in Numpy this is possible to perform such operation by using broadcasting.

A = np.array([[10, 20, 30], [15, 25, 35]])

B = np.array([10, 25, 35])

C = A + B


[[10 20 30]
 [15 25 35]]
[10 25 35]
[[20 45 65]
 [25 50 70]]