Introduction
This tutorial will introduce the concept of broadcasting in NumPy library. Broadcasting is a method of performing mathematical operations on arrays of various dimensions.
VM Tips
After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.
Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.
If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.
Adding Two 1D Arrays of the Same Shape
import numpy as np
a = np.array([1,2,3,4])
b = np.array([2,7,8,9])
c = a+b;
print(c)
The output will be: [ 3 9 11 13]
Attempting to Add Two 1D Arrays with Different Shapes
import numpy as np
a = np.array([4,5,6,7])
b = np.array([1,3,5,7,9,11,14])
c = a+b;
This will produce an error because you cannot perform operations on arrays with different shapes.
Using Broadcasting to Add Two 1D Arrays with Different Shapes
import numpy as np
a = np.array([4,5,6,7])
b = np.array([10])
c = a+b;
print(c)
This will output [14 15 16 17] since array b is being broadcast across array a.
Broadcasting a 1D Array into a 2D Array
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([10, 20, 30])
print(a + b)
The output will be:
[[11 22 33]
[14 25 36]]
The 1D array is broadcast across the second axis of the 2D array and added to each column.
Multiplying Arrays of Different Dimensions
import numpy as np
a = np.array([1, 2, 3])
b = np.array([[4, 5, 6], [7, 8, 9]])
print(a * b)
The output will be:
[[ 4 10 18]
[ 7 16 27]]
The 1D array is broadcast across the first axis of the 2D array and multiplied to each row.
Summary
In this tutorial, we covered the concept of broadcasting in the NumPy library. Broadcasting is a method of performing mathematical operations on arrays of various dimensions. We also demonstrated how broadcasting works via adding and multiplying arrays. It is important to note that broadcasting can only be done if arrays satisfy certain conditions. Broadcasting only occurs if it doesn’t lead to a loss of information.