- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# How to Perform Numpy Broadcasting using Python using dynamic arrays?

"Broadcasting” refers to how NumPy handles arrays of different dimensions during arithmetic operations. The smaller array is "broadcast" across the larger array, subject to certain limits, to ensure that their shapes are consistent. Broadcasting allows you to vectorize array operations, allowing you to loop in C rather than Python."

This is accomplished without the need for unnecessary data copies, resulting in efficient algorithm implementations. In some cases, broadcasting is a negative idea since it results in wasteful memory utilization, which slows down the computation.

In this article, we will show you how to perform broadcasting with NumPy arrays using python.

## Steps to perform Broadcasting on give array −

Step 1. Create two arrays of compatible dimensions

Step 2. Print the given array

Step 3. Perform arithmetic operation with the two arrays

Step 4. Print the result array

## Adding Two Arrays of Different Dimensions

Create a numpy array consisting numbers from 0 to n-1 using the arange() function (The arange() function returns values that are evenly spaced within a given interval. Within the half-open interval [start, stop], values are generated) and add some constant number to it.

### Example

import numpy as np # Getting list of numbers from 0 to 7 givenArray = np.arange(8) # Adding a number to the numpy array result_array = givenArray + 9 print("The input array",givenArray) print("Result array after adding 9 to the input array",result_array)

### Output

The input array [0 1 2 3 4 5 6 7] Result array after adding 9 to the input array [ 9 10 11 12 13 14 15 16]

The given array has one dimension (axis) with a length of 8, whereas 9 is a simple integer with no dimensions. Since their dimensions differ, Numpy tries to broadcast (just stretch) the smaller array along a certain axis, making it acceptable for the mathematical operation.

## Summing both the arrays with compatible dimensions

Creating two NumPy arrays from 0 to n-1 using the arange() function and reshaping it with reshape() function(reshapes an array without affecting its data). The two arrays are with compatible dimensions (3,4) and (3,1) and adding the corresponding elements of both the arrays.

### Example

import numpy as np # Getting the list of numbers from 0 to 11 and reshaping it to 3 rows and 4 columns givenArray_1 = np.arange(12).reshape(3, 4) # Printing the shape(rowsize, columnsize) of array print("The shape of Array_1 = ", givenArray_1.shape) # Getting list of numbers from 0 to 2 and reshaping it to 3 rows and 1 columns givenArray_2 = np.arange(3).reshape(3, 1) print("The shape of Array_2 = ", givenArray_2.shape) # Summing both the arrays print("Input array 1 \n",givenArray_1) print("Input array 2 \n",givenArray_2) print("Summing both the arrays:") print(givenArray_1 + givenArray_2)

### Output

The shape of Array_1 = (3, 4) The shape of Array_2 = (3, 1) Input array 1 [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] ] Input array 2 [[0] [1] [2]] Summing both the arrays: [[ 0 1 2 3] [ 5 6 7 8] [10 11 12 13]]

The givenArray_2 is expanded along the second dimension to match the dimension of givenArray_1. As the dimensions of both the arrays are compatible this can be made possible.

## Summing both the arrays with INCOMPATIBLE dimensions

Creating two NumPy arrays with INCOMPATIBLE dimensions (6, 4) and (6, 1). When we try to add the corresponding elements of both the arrays it raises an ERROR as shown below.

### Example

import numpy as np # Getting a list of numbers from 0 to 11 and reshaping it to 3 rows and 4 columns givenArray_1 = np.arange(20).reshape(6, 4) # Printing the shape(rowsize, columnsize) of array print("The shape of Array_1 = ", givenArray_1.shape) # Getting list of numbers from 0 to 5 and reshaping it to 3 rows and 1 columns givenArray_2 = np.arange(6).reshape(6, 1) print("The shape of Array_2 = ", givenArray_2.shape) # Summing both the arrays print("Summing both the arrays:") print(givenArray_1 + givenArray_2)

### Output

Traceback (most recent call last): File "main.py", line 3, ingivenArray_1 = np.arange(20).reshape(6, 4) ValueError: cannot reshape array of size 20 into shape (6,4)

The number of rows is 6, and the number of columns is 4.

It cannot be inserted in a matrix of size 20 (it requires a matrix of size 6*4 = 24).

## Summing Numpy Multidimensional Array and Linear Array

Create an multidimensional array using the arange() function and reshape it to some random number of rows and columns using the reshape() function. Create Another linear array using the arange() function and sum both these arrays.

### Example 1

import numpy as np # Getting list of numbers from 0 to 14 and reshaping it to 5 rows and 3 columns givenArray_1 = np.arange(15).reshape(5, 3) # Printing the shape(rowsize, columnsize) of array print("The shape of Array_1 = ", givenArray_1.shape) # Getting list of numbers from 0 to 2 givenArray_2 = np.arange(3) print("The shape of Array_2 = ", givenArray_2.shape) # Summing both the arrays print("Array 1 \n",givenArray_1) print("Array 2 \n",givenArray_2) print("Summing both the arrays: \n",givenArray_1 + givenArray_2)

### Output

The shape of Array_1 = (5, 3) The shape of Array_2 = (3,) Array 1 [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11] [12 13 14]] Array 2 [0 1 2] Summing both the arrays: [[ 0 2 4] [ 3 5 7] [ 6 8 10] [ 9 11 13] [12 14 16]]

The given linear Array is expanded to match the dimension of given array 1 (Multidimensional Array). As the dimensions of both the arrays are compatible this can be made possible.

### Example 2

import numpy as np givenArray_1 = np.arange(240).reshape(6, 5, 4, 2) print("The shape of Array_1: ", givenArray_1.shape) givenArray_2 = np.arange(20).reshape(5, 4, 1) print("The shape of Array_2: ", givenArray_2.shape) # Summing both the arrays and printing the shape of it print("Summing both the arrays and printing the shape of it:") print((givenArray_1 + givenArray_2).shape)

### Output

The shape of Array_1: (6, 5, 4, 2) The shape of Array_2: (5, 4, 1) Summing both the arrays and printing the shape of it: (6, 5, 4, 2)

It is critical to understand that multiple arrays can be propagated along several dimensions. Array1 has dimensions (6, 5, 4, 2), whereas array2 has dimensions (5, 4, 1). The dimension array is formed by stretching array1 along the third dimension and array2 along the first and second dimensions(6, 5, 4, 2).

## Conclusion

Numpy broadcasting is faster than looping across an array. Begin with the first example. Instead of using the broadcasting approach, the user can loop through an array, adding the same number to each element in the array. This is slow for two reasons: looping requires interfacing with the Python loop, which slows down the C implementation. Second, NumPy uses strides instead of loops. Setting strides to 0 allows you to loop through the components endlessly with no memory overhead.

- Related Articles
- Broadcasting with NumPy Arrays in Python
- Add two vectors using broadcasting in Numpy
- Discuss broadcasting in Numpy in Python?
- C++ Program to Perform Optimal Paranthesization Using Dynamic Programming
- Perform element-wise comparison of two string arrays using a comparison operator in Numpy
- How to perform accurate Decimal Calculations using Python?
- How to perform image transpose using OpenCV Python?
- How to perform image translation using OpenCV in Python?
- How to perform image rotation in OpenCV using Python?
- How to perform dimensionality reduction using Python Scikit-learn?
- How to Flatten a Matrix using numpy in Python?
- How to create dynamic breadcrumbs using JavaScript?
- How to perform sort using Java?
- How to perform square root without using math module in Python?
- How to perform Matrix Addition using C#?