Broadcasting with NumPy Arrays in Python


We know the arithmetic operations between different arrays happens monthly if the arrays are of equal size awesome required specific size. But there are scenarios when we can take erase of unequal size and still apply arithmetic operations on them by enhancing one of the arrays by filling array with smaller ndim prepended with '1' in its shape. So basically broadcasting and array means changing its shape to any required shape.

Rules of array Boradcasting

  • Array with smaller ndim than the other is prepended with '1' in its shape.

  • Size in each dimension of the output shape is maximum of the input sizes in that dimension.

  • An input can be used in calculation, if its size in a particular dimension matches the output size or its value is exactly 1.

  • If an input has a dimension size of 1, the first data entry in that dimension is used for all calculations along that dimension.

Example

The below example shows how the broadcasting happens during array manipulation using numpy arrays.

 Live Demo

import numpy as np
a = np.array([[0.0,0.0,0.0],[10.0,10.0,10.0],[20.0,20.0,20.0],[30.0,30.0,30.0]])
b = np.array([1.0,2.0,3.0])

print 'First array:'
print a
print '\n'

print 'Second array:'
print b
print '\n'

print 'First Array + Second Array'
print a + b

Output

Running the above code gives us the following result −

First array:
[
   [ 0. 0. 0.]
   [ 10. 10. 10.]
   [ 20. 20. 20.]
   [ 30. 30. 30.]
]

Second array:
[ 1. 2. 3.]

First Array + Second Array
[
   [ 1. 2. 3.]
   [ 11. 12. 13.]
   [ 21. 22. 23.]
   [ 31. 32. 33.]
]

Updated on: 22-Jul-2020

111 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements