## Introduction to NumPy Broadcasting

Broadcasting in NumPy denotes the ability to treat arrays of several shapes while performing arithmetic operations. These operations on arrays are commonly performed on corresponding elements. It can be easily done on 2 arrays if they are in the same shape. Even though this is the case, broadcasting is considered as a bad idea as it can lead to ineffective memory usage that slows down the computation process. The operations on NumPy are normally done on array pairs that are on an element-by-element basis. Even if the method was developed for NumPy, other computational libraries like TensorFlow, Octave, and Theano also use this.

### How Broadcasting work in NumPy?

In broadcasting, certain rules have to be followed.

**Rule no. 1:**If two arrays do not have the matching rank, the lower rank array shape has to be prepended with 1s till the both array shapes have the exact same length.**Rule no. 2:**If two arrays have the same dimension size or one array has 1 as the dimension size, then those two arrays are said to be compatible.**Rule no. 3:**Only if the arrays are compatible with the size/dimensions, the arrays can be broadcasted together.**Rule no. 4:**Once the broadcasting is done, each and every array behaves as if it has shape same as the maximum in the element-wise shapes of the both input arrays.**Rule no. 5:**If one of the array has dimension as 1 and the other array has a dimension larger than 1, then the array 1 acts as if it was copied with that dimension.

An array set is said to be broadcastable only if the above-mentioned rules generate a valid result and 1 of the below conditions is true.

- Arrays have accurately the similar shape.
- Arrays have count of dimensions same and each dimension length is either the same length or 1.
- Array that contains too less dimensions can prepend the shape with a dimension of 1, so that the above mentioned property is true.

**Example:**

**Code:**

```
import numpy as np
p = np.array([11,22,23,24])
q = np.array([10,40,50,60])
r = p * q
print (r)
```

In this program, the two arrays are compatible as they are of same size. So, on executing the code, the result will be as shown below.

**Output:**

Suppose the dimensions of the two provided arrays are not similar, then it is not possible to perform the element-to-element operations. Moreover, error will be displayed on executing the code. However, arrays of dissimilar shapes perform operations with the help of NumPy, due to its broadcasting capability.

### Examples of NumPy Broadcasting

Given below are the examples of NumPy Broadcasting:

#### Example #1

Python program that broadcast 3 dimensional array.

**Code:**

```
import numpy as np
arr1 = np.array( [ [ 2 , 32, 43, 54] , [ 22, 54, 65, 76] , [60 ,70 ,89 ,36]] )
arr2 = np.array([ 24, 45, 66, 87] )
print("\n first array : ")
print(arr1)
print("\n second array: ")
print(arr2)
print("\nResult of the sum of first and second array: ")
sum = arr1 + arr2 ;
print(sum)
```

**Output:**

In this program, two arrays are declared where the first array is of 3-dimension. On executing the code, the sum of first and second array will be displayed as shown above.

#### Example #2

Python program that broadcast 1 dimensional array.

**Code:**

```
import numpy as np
arr1 = np.array( [ 2 , 32, 43] )
arr2 = np.array([87])
print("\n first array : ")
print(arr1)
print("\n second array: ")
print(arr2)
print("\nResult of the sum of first and second array: ")
sum = arr1 + arr2 ;
print(sum)
```

**Output:**

Similar to the above program, in this program also, two arrays are declared where the first array is of 1-dimension. On executing the code, the sum of first and second array will be displayed as shown above.

#### Example #3

Python program that broadcast 2 dimensional array.

**Code:**

```
import numpy as np
arr1 = np.array( [ [ 2 , 32, 43, 54] , [ 22, 54, 65, 76] ])
arr2 = np.array([24,45,66,87])
print("\n first array : ")
print(arr1)
print("\n second array: ")
print(arr2)
print("\nResult of the sum of first and second array: ")
sum = arr1 + arr2 ;
print(sum)
```

**Output:**

Similar to the above two programs, in this program also, two arrays are declared first. The difference is that the first array is of 2-dimension. On executing the code, the sum of first and second array will be displayed as shown above.

#### Example #4

Simple python program on broadcasting function.

**Code:**

```
import numpy as np
a = np.array([22, 54, 46])
b = np.array([25, 35])
print(np.reshape( a, (3, 1 ) ) * b )
r = np.array([[32, 42, 23], [35, 35, 26]])
print(r + a)
print((r.T + b).T)
print(r + np.reshape(b, (2, 1 ) ) )
print(r * 2)
```

**Output:**

In this program, two arrays are declared first. In order to calculate an outer product, a has to be reshaped to a column vector of 3×1 shape. Once this is done, broadcast is done against b in order to obtain a result of size 3×2 which is called as the outer product of a and b. Since r has the shape 2×3 as well as a has shape (3, ), broadcasting can be done to 2×3. After completing all these steps, a vector has to be added to each and every column of a matrix r that has the dimension 2×3 and b has dimension (2, ) If we transpose r, shape will be 3×2 and as a result, it can be broadcast against b for obtaining the shape 3×2. Normally, transposing this results in a final result of shape 2×3.

### Conclusion

Broadcasting in NumPy denotes the ability to treat arrays of several shapes while performing arithmetic operations which are commonly performed on corresponding elements.

### Recommended Articles

This is a guide to NumPy Broadcasting. Here we discuss the introduction, how broadcasting work in NumPy? along with examples respectively. You may also have a look at the following articles to learn more –

4 Online Courses | 5 Hands-on Projects | 37+ Hours | Verifiable Certificate of Completion

4.5

View Course

Related Courses