NumPy broadcast_to() Function:
The broadcast to() function in the NumPy module broadcasts an array to a new shape.
Syntax:
numpy.broadcast_to(array, shape, subok=False)
Parameters
array: This is required. It is the array to be broadcasted.
shape: This is required. It is the required array’s shape.
subok: This is optional. Sub-classes will be sent through if True; otherwise, the returned array will be forced to be a base-class array (default).
Return Value:
Sub-classes will be sent through if True; otherwise, the returned array will be forced to be a base-class array (default).
If the array is not compatible with the new shape according to NumPy’s broadcasting rules, a ValueError is raised.
NumPy broadcast_to() Function in Python
Example1
Approach:
- Import numpy module using the import keyword.
- Give the random list as an argument to the array() function to create the array and store it in a variable.
- Give the other random list as an argument to the array() function to create the other array and store it in another variable.
- Pass the above “p” array, shape(rowsize, colsize) as an argument to broadcast_to() function to broadcast it to the given shape(3, 3).
- Store it in another variable.
- Print the above result.
-
The Exit of the Program.
Below is the implementation:
# Import numpy module using the import keyword import numpy as np # Give the random list as an argument to the array() function # to create an array and store it in a variable. p = np.array([4, 1, 5]) # Give the other random list as an argument to the array() function # to create the other array and store it in another variable. q = np.array([8, 9]) # Pass the above "p" array, shape(rowsize, colsize) as an argument to # broadcast_to() function to broadcast it to the given shape(3, 3) # Store it in another variable. rslt = np.broadcast_to(p, (3, 3)) # Print the above result print("The result after broadcasting p:") print(rslt)
Output:
The result after broadcasting p: [[4 1 5] [4 1 5] [4 1 5]]
Example2
Similarly, do the same for the q Array.
# Import numpy module using the import keyword import numpy as np # Give the random list as an argument to the array() function # to create an array and store it in a variable. q = np.array([8, 9]) # Pass the above "q" array, shape(rowsize, colsize) as an argument to # broadcast_to() function to broadcast it to the given shape(3, 2) # Store it in another variable. rslt = np.broadcast_to(q, (3,2)) # Print the above result print("The result after broadcasting q:") print(rslt)
Output:
The result after broadcasting q: [[8 9] [8 9] [8 9]]