Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

NumPy: broadcast_to() function

numpy.broadcast_to() function

The broadcast_to() function is used to produce an object that mimics broadcasting.

Syntax:

numpy.broadcast_to(array, shape, subok=False)
NumPy manipulation: broadcast_to() function

Version: 1.15.0

Parameter:

Name Description Required /
Optional
array The array to broadcast. Required
shape The shape of the desired array. Required
subok If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default). Optional

Return value:

If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default).

Raises: ValueError - If the array is not compatible with the new shape according to NumPy’s broadcasting rules.

Example-1: numpy.broadcast_to()

>>> import numpy as np
>>> a = np.array([2,3,4])
>>> np.broadcast_to(a, (3, 3))
array([[2, 3, 4],
       [2, 3, 4],
       [2, 3, 4]])

Pictorial Presentation:

Python NumPy manipulation: broadcast_to() function

Example-2: numpy.broadcast_to()

>>> import numpy as np
>>> from numpy import array
>>> x = array([[2, 3, 4], [2, 3, 4]])
>>> print(x.shape)
(2, 3)

Pictorial Presentation:

NumPy manipulation: broadcast_to() function

Example-3: numpy.broadcast_to()

>>> import numpy as np
>>> y = array([2, 3])
>>> print(y.shape)
(2,)

Pictorial Presentation:

NumPy manipulation: broadcast_to() function

Example-4: numpy.broadcast_to()

>>> import numpy as np
>>> x = np.ma.array([2, 3, 4], mask=[False, True, False])
>>> y = np.broadcast_to(x, (3, 3), subok=True)
>>> y.mask
False
>>> y.mask = np.broadcast_to(x.mask, y.shape)
>>> y
masked_array(data =
 [[2 -- 4]
 [2 -- 4]
 [2 -- 4]],
             mask =
 [[False  True False]
 [False  True False]
 [False  True False]],
       fill_value = 999999)

Python - NumPy Code Editor:

Previous: broadcast
Next: broadcast_arrays()