Categories: NumpyPython

Broadcasting of Numpy arrays in Python

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.

wilsonzhang746

Recent Posts

Download R Course source files

Click here to download R Course source files !

2 months ago

Download Python Course source files

Click here to download Python Course Source Files !

2 months ago

How to create a data frame from nested dictionary with Pandas in Python

For online Python training registration, click here ! Pandas provides flexible ways of generating data…

5 months ago

How to delete columns of a data frame in Python

For online Python training registration, click here ! Data frame is the tabular data object…

5 months ago

Using isin() to check membership of a data frame in Python

Click her for course registration ! When a data frame in Python is created via…

5 months ago

How to assign values to Pandas data frame in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…

5 months ago