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 source files for R Machine learning

Click here to go to source files for R Machine Learning

3 days ago

Python Machine Learning Source Files

Click here to download Python Machine Learning Source Files !

4 weeks ago

Install PyTorch on Windows

PyTorch is a deep learning package for machine learning, or deep learning in particular for…

1 month ago

Topic Modeling using Latent Dirichlet Allocation with Python

Topic modeling is a subcategory of unsupervised machine learning method, and a clustering task in…

2 months ago

Document sentiment classification using bag-of-words in Python

For online Python training registration, click here ! Sentiment classification is a type of machine…

2 months ago

Download R Course source files

Click here to download R Course source files !

11 months ago