Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Broadcasting | Math with NumPy
Ultimate NumPy
course content

Course Content

Ultimate NumPy

Ultimate NumPy

1. NumPy Basics
2. Indexing and Slicing
3. Commonly used NumPy Functions
4. Math with NumPy

bookBroadcasting

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:

  1. Shape Comparison: NumPy compares the shapes of the two arrays starting from the rightmost dimension and moving left;

  2. Compatibility Conditions: Two dimensions are considered compatible if:

    • They are the same size (equal);
    • One of the dimensions is 1.
  3. 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.

Select arrays with compatible shapes:

Select arrays with compatible shapes:

Select a few correct answers

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 1
We're sorry to hear that something went wrong. What happened?
some-alt