Instagram
youtube
Facebook
Twitter

Broadcasting in Numpy

NumPy is a great library for numerical and array operations in Python. One of its most useful features is broadcasting. In this tutorial, we will explore broadcasting in NumPy and learn how to use it effectively.

What is Broadcasting?

  • Broadcasting is a feature, in NumPy that enables us to perform element-wise operations on arrays with different shapes.

  • It functions by adjusting the array to match the shape of the larger one allowing for seamless element wise operations without the need of explicitly reshaping or duplicating data.

  • This feature is very essential, in simplifying array operations within NumPy.

Broadcasting Rules

NumPy follows a set of rules in broadcasting to determine how arrays with different shapes can be combined. These rules are:

  • Rule 1: If the arrays have different dimensions, pad the smaller array's shape with ones on the left side until both shapes have the same length.

  • Rule 2: Compare the dimensions element-wise. Two dimensions are compatible when they are equal, or one of them is 1. If these conditions are not met, NumPy raises a ValueError.

Some Examples of Broadcasting

Here are some examples to understand how broadcasting works.

Example 1: Broadcasting a Scalar

import numpy as np
array1 = np.array([2,4,6,8])
num = 5 #Scalar
result = array1*num
print(result)

Result:

[10 20 30 40]

Here, 5(scalar) is broadcasted to match the shape of array1.

Example 2: Broadcasting Arrays with Different Shapes

import numpy as np
array1 = np.array([[2,4,6,8],[1,1,1,1]])
array2 = np.array([3,6,9,12])
result = array1+array2
print(result)

Result:

[[ 5 10 15 20]
 [ 4  7 10 13]]

Here, the smaller array "B" is broadcasted to match the shape of the larger array "A".

Example 3: Broadcasting Arrays with Different Shapes

import numpy as np
array1 = np.array([[2,4],[1,1]])
array2 = np.array([3,6,9,12])
result = array1+array2
print(result)

Result:

ValueError: operands could not be broadcast together with shapes (2,2) (4,)

So from the above example, it is clear that arrays with incompatible shapes can't be broadcast.