EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

NumPy Broadcasting

Home » Software Development » Software Development Tutorials » NumPy Tutorial » NumPy Broadcasting

NumPy Broadcasting

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 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.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

  • 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 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 generates 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:

NumPy Broadcasting 1

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:

NumPy Broadcasting 2

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.

Popular Course in this category
Pandas and NumPy Tutorial (4 Courses, 5 Projects)4 Online Courses | 5 Hands-on Projects | 37+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (4,870 ratings)
Course Price

View Course

Related Courses
Python Training Program (36 Courses, 13+ Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)

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:

NumPy Broadcasting 3

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:

2 dimensional array

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:

Simple python program

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 –

  1. numpy.linspace()
  2. NumPy.argmax()
  3. numpy.dot()
  4. numpy.diff()

All in One Software Development Bundle (600+ Courses, 50+ projects)

600+ Online Courses

50+ projects

3000+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
NumPy Tutorial
  • Basics
    • Introduction to NumPy
    • Install NumPy
    • NumPy Data Types
    • NumPy Functions
    • NumPy Histogram
    • numPy.where()
    • numpy.sort
    • NumPy floor()
    • Matrix in NumPy
    • Matrix Multiplication in NumPy
    • NumPy Arrays
    • NumPy Array Functions
    • NumPy Ndarray
    • NumPy Array Append
    • NumPy empty array
    • NumPy ndarray tolist
    • numpy.linspace()
    • NumPy.argmax()
    • NumPy Linear Algebra
    • numpy.diff()
    • numpy.unique( )
    • NumPy zeros
    • numpy.mean()
    • numpy.dot()
    • Numpy.argsort()
    • numpy.pad()
    • numpy.ravel()
    • NumPy stack
    • NumPy vstack
    • NumPy hstack
    • NumPy sum
    • NumPy cumsum
    • NumPy max
    • NumPy squeeze
    • NumPy median
    • NumPy Round
    • NumPy NaN
    • NumPy divide
    • NumPy square
    • NumPy ones
    • NumPy Meshgrid
    • NumPy exponential
    • NumPy percentile
    • NumPy fft
    • NumPy flatten
    • NumPy Concatenate
    • NumPy Outer
    • NumPy zip
    • NumPy Newaxis
    • NumPy Format
    • Numpy Random Seed ()
    • NumPy random choice
    • NumPy random normal
    • NumPy unravel_index
    • Numpy.eye()
    • NumPy append
    • NumPy searchsorted
    • NumPy shape
    • NumPy reshape
    • NumPy savetxt
    • NumPy genfromtxt
    • NumPy standard deviation
    • NumPy covariance
    • NumPy repeat
    • NumPy?Tile
    • NumPy Broadcasting

Related Courses

Pandas And NumPy Training Course

Python Training Course

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - Pandas And NumPy Training Course Learn More