Course Content
Ultimate NumPy
Ultimate NumPy
Broadcasting
Before we dive into the mathematical operations in NumPy, let’s take a closer look at an important concept: broadcasting.
If two arrays already have the same number of dimensions, there is no need for extending.
Determining Compatibility of Shapes
Given two arrays, NumPy checks their shapes to determine if they can be broadcast together. Here's how it works:
-
Shape Comparison: NumPy compares the shapes of the two arrays starting from the rightmost dimension and moving left;
-
Compatibility Conditions: Two dimensions are considered compatible if:
- They are the same size (equal);
- One of the dimensions is
1
.
-
Handling Different Number of Dimensions: If one array has fewer dimensions than the other, the missing dimensions are treated as having size
1
.
Don't worry, here are some examples to clarify things:
As you can see, a scalar in our example is broadcast to a 1D array.
A scalar can now be broadcast to a 2D array. In fact, a scalar is always compatible with an array of any shape.
In this example, a 1D array is broadcast to a 2D array since their shapes are compatible.
Here we have a 1D array with a shape incompatible with our 2D array, as their right dimensions are not equal.
Thanks for your feedback!