Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Numpy broadcast_to() Function



Numpy broadcast_to() Function which broadcasts an array to a new shape. It mimics the broadcasting mechanism of creating a new view on the array with the specified shape without actually copying the data.

This can be useful for making arrays of compatible shapes for operations without duplicating data.

Syntax

Following is the syntax of numpy.broadcast_to function −

numpy.broadcast_to(array, shape, subok=False)

Parameters

Below are the Parameters of the numpy.broadcast_to function −

  • array: The array to broadcast.
  • shape(tuple): The shape to which the array is to be broadcasted.
  • subok(bool, optional): If this Parameter is True then sub-classes will be passed-through, otherwis the returned array will be forced to be a base-class array. Default Value is False.

Return Value

It returns a read-only view on the original array with the given shape. It will have a read-only attribute which is set to True.

Example 1

Following is the example of broadcasting a 1D array to a 2D shape with the help of Numpy broadcast_to() Function. Here in this example the 1D array [1, 2, 3] is broadcasted to a 2D array of shape (3, 3).

import numpy as np

# Original array
arr = np.array([1, 2, 3])

# Broadcasting to shape (3, 3)
broadcasted_arr = np.broadcast_to(arr, (3, 3))

print("Original array:")
print(arr)
print("\nBroadcasted array:")
print(broadcasted_arr)

Output

Original array:
[1 2 3]

Broadcasted array:
[[1 2 3]
 [1 2 3]
 [1 2 3]]

Example 2

We can broadcast a 2D array to a higher dimensional shape with the help of numpy.broadcast_to() function. Here, the 2D array [[1, 2], [3, 4]] is broadcasted to a 3D array of shape (2, 2, 2) −

import numpy as np

# Original 2D array
arr = np.array([[1, 2], [3, 4]])

# Broadcasting to shape (2, 2, 2)
broadcasted_arr = np.broadcast_to(arr, (2, 2, 2))

print("Original array:")
print(arr)
print("\nBroadcasted array:")
print(broadcasted_arr)

Output

Original array:
[[1 2]
 [3 4]]

Broadcasted array:
[[[1 2]
  [3 4]]

 [[1 2]
  [3 4]]]

Example 3

Below example shows how numpy.broadcast_to() function efficiently replicates a given array to a new shape by expanding its contents without duplicating data −

import numpy as np 
a = np.arange(4).reshape(1,4) 

print('The original array:') 
print(a)
print('\n')  

print('After applying the broadcast_to function:') 
print(np.broadcast_to(a,(4,4)))

Output

The original array:
[[0 1 2 3]]


After applying the broadcast_to function:
[[0 1 2 3]
 [0 1 2 3]
 [0 1 2 3]
 [0 1 2 3]]
numpy_array_manipulation.htm
Advertisements