We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental level, click here for more details.

If two Numpy arrays may having different shapes take operations, e.g. addition or subtraction, and their shapes are compatible for such operation. This is called broadcasting. The prerequisite of broadcasting is that either two arrays have the same shapes, or at least one axis of an array is 1. In the latter case, this axis will be extended to be the same shape of the corresponding axis of the other array, and filled with the same contents of the existing ones. We show an example of such mechanism in the following code.

#Import Numpy module
import numpy as np
#create an array of shape (6,3)
T1 = np.arange(18).reshape(6, 3)
T1
#output
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [12, 13, 14],
       [15, 16, 17]])
#create an array of shape (6,)
T2 = np.arange(6)
#output
T2
array([0, 1, 2, 3, 4, 5])
#reshape T2 to shape (6,1)
T2 = T2.reshape(6,1)
#perform addition of two arrays
T1 + T2
#result
array([[ 0,  1,  2],
       [ 4,  5,  6],
       [ 8,  9, 10],
       [12, 13, 14],
       [16, 17, 18],
       [20, 21, 22]])

As you can see, the results are the same as each row of T1 is added by a T2.

You can also watch videos on our YouTube channel for more understanding of Python programming skills.


0 Comments

Leave a Reply

Avatar placeholder