Trusted answers to developer questions

What is broadcasting in Numpy?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

It is impossible to carry out certain arithmetic operations if two arrays have different shapes. In this situation, Python provides you with a built-in numpy.array() broadcasting feature that broadcasts the smaller array across the larger array. Take a look at the example below:

svg viewer

Solution

As stated earlier, we will broadcast the smaller array across the larger array to perform this arithmetic operation.

svg viewer

Possible cases

One of the possible cases (shown above) that makes broadcasting possible is when two matrices have the same columns. However​, we have two more cases:

1 of 2

Code

# importing numpy library
import numpy as np
# MatA is a 3x3 matrix
MatA = np.array([[1,2,3],[4,5,6],[7,8,9]])
# MatB is also a 1x3 matrix
MatB = np.array([[1],[2],[3]])
# Arithmetic operation is possible because
# of broadcasting
print (MatA + MatB)

RELATED TAGS

numpy
python 3
broadcast
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?