Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

numpy
python
communitycreator

What is the numpy.broadcast_to() function in NumPy?

Onyejiaku Theophilus Chidalu

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

The broadcast_to() function in NumPy is used to broadcast a given array to a new shape.

Broadcasting in NumPy describes how NumPy treats arrays with different shapes to make them suitable for different arithmetic operations.

To learn more about broadcasting in NumPy, you can read this shot.

Syntax

numpy.broadcast_to(array, shape, subok=False)
Syntax for the broadcast_to() function in NumPy

Parameter value

The broadcast_to() function takes the following parameter values:

  • array: This is the input array to be broadcast. This is a required parameter.
  • shape: This is the shape of the output array. This is a required parameter.
  • subok: This takes a logical value (True or False) indicating if the sub-classes will be passed through or if it will be a base-class array. This is an optional parameter.

Return value

The broadcast_to() function returns a read-only view on the input array with the given shape.

Example

import numpy as np
# creating an input array
a = np.array([1,2,3,4,5,6,7,8])
# implementing the broadcast_to() function
myarray = np.broadcast_to(a, (8,8))
# printing the broadcasted array
print(myarray)
Implementing the broadcast_to() function

Code explanation

  • Line 1: We import the numpy module.
  • Line 3: We create an input array, a, using the array() function.
  • Line 6: We broadcast the array, a, to a new shape that has 8 rows and 8 columns, using the broadcast_to() function. We assigned the result to a variable, myarray.
  • Line 9: We print the new array, myarray.

RELATED TAGS

numpy
python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring