Discuss broadcasting in Numpy in Python?

PythonServer Side ProgrammingProgramming

NumPy refers to ‘Numerical’ ‘Python’. It is a library that contains multidimensional array objects and multiple methods that help in processing the arrays.

NumPy can be used to perform a wide variety of operations on arrays. It is used in conjunction with packages like SciPy, Matplotlib and so on. NumPy+Matplotlib can be understood as an alternative to MatLab. It is an open-source package, which means it can be used by anyone. Standard Python distribution doesn’t include NumPy package by default. The package has to be separately installed using the installer ‘pip’.

For Windows, it has been shown below −

pip install numpy

Once this command is executed on the command line, it can be imported into the Python environment and used.

The most important object present in NumPy package is an n-dimensional array which is known as ‘ndarray’. It defines the collection of items of the same type. These values inside the ndarray can be accessed using indexing (0-based index). Every item in the ndarray takes the same size of block in the memory space. Every element’s type in the ndarray can be found using the ‘dtype’ function. An item from the ndarray can be extracted using array slicing. It is represented as an object of array scalar type.

With respect to Numpy array, broadcasting refers to the ability of this package to treat arrays that are of different shapes during arithmetic operations. If two arrays are not of same type, no error is thrown up. Instead, the operations go on smoothly.

Example

 Live Demo

import numpy as np
arr_1 = np.array([4, 6, 8, 0, 3])
arr_2 = np.array([11,3,7,78, 999])
print("The first ndarray is ")
print(arr_1)
print("The second ndarray is ")
print(arr_2)
arr_3 = arr_1 * arr_2
print("The resultant array is ")
print(arr_3)

Output

The first ndarray is
[4 6 8 0 3]
The second ndarray is
[ 11 3 7 78 999]
The resultant array is
[ 44 18 56 0 2997]

Explanation

  • The required libraries are imported into Python environment.

  • Two ndarrays are defined with numeric values inside them.

  • They ae printed on the console.

  • The third array is defined as the product of the first two ndarrays.

  • The resultant array is displayed on the console.

raja
Updated on 11-Dec-2020 11:34:09

Advertisements