What is the numpy.broadcast_to() function in NumPy?
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 (TrueorFalse) 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 arraya = np.array([1,2,3,4,5,6,7,8])# implementing the broadcast_to() functionmyarray = np.broadcast_to(a, (8,8))# printing the broadcasted arrayprint(myarray)
Code explanation
- Line 1: We import the
numpymodule. - Line 3: We create an input array,
a, using thearray()function. - Line 6: We broadcast the array,
a, to a new shape that has8rows and8columns, using thebroadcast_to()function. We assigned the result to a variable,myarray. - Line 9: We print the new array,
myarray.