NumPy Broadcasting

in StemSocial12 hours ago

image.png

Image Source

Today we will look into broadcasting in NumPy. Broadcasting is a powerful feature that allows NumPy to perform arithmetic operations on arrays of different shapes and sizes, without explicitly reshaping them. This is particularly useful when working with arrays of different dimensions but performing similar operations.

Let’s look at an example where broadcasting helps us add a scalar to a 2D array.

Here’s the code:

import numpy as np

# Creating a 2D array of size 3x3
array_1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Adding a scalar (constant) to every element of the array
result_array = array_1 + 10

print("Original Array:")
print(array_1)

print("\nArray After Addition:")
print(result_array)


In the code above, we created a 3x3 array, and then added a scalar value 10 to each element of the array. Due to broadcasting, NumPy automatically applies the scalar value to each element without needing any loop or explicit reshaping.

The output will look like this:

image.png

Now let’s see another common use of broadcasting—adding a 1D array to a 2D array. We’ll add a 1D array to each row of the 2D array.

# Creating a 1D array
array_2 = np.array([1, 2, 3])

# Adding the 1D array to each row of the 2D array
broadcasted_result = array_1 + array_2

print("\nArray After Broadcasting Addition:")
print(broadcasted_result)


In this case, NumPy automatically broadcasts the 1D array across each row of the 2D array, adding the corresponding elements.

This is what the output will look like:

image.png

As you can see, NumPy handled the broadcasting operation automatically, adding each element of the 1D array to the corresponding row of the 2D array. This makes the process much more efficient than manually looping through the rows and columns.

Broadcasting is very powerful because it will save you a lot of time and memory when dealing with arrays of complex shapes and sizes. It's a feature you’ll use often when working with large datasets or mathematical operations in NumPy.