np.broadcast_to函数将数组广播到新形状。
In [1]: import numpy as np
In [3]: a = np.arange(4).reshape(1,4)
In [4]: a
Out[4]: array([[0, 1, 2, 3]])
In [5]: np.broadcast_to(a,(4,4))
Out[5]:
array([[0, 1, 2, 3],
[0, 1, 2, 3],
[0, 1, 2, 3],
[0, 1, 2, 3]])
它在原始数组上返回只读视图。 它通常不连续。 如果新形状不符合 NumPy 的广播规则,该函数可能会抛出ValueError
。
In [6]: np.broadcast_to(a,(4,3))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-6-bd347948d6c4> in <module>()
----> 1 np.broadcast_to(a,(4,3))
~\Anaconda3\lib\site-packages\numpy\lib\stride_tricks.py in broadcast_to(array, shape, subok)
171 [1, 2, 3]])
172 """
--> 173 return _broadcast_to(array, shape, subok=subok, readonly=True)
174
175
~\Anaconda3\lib\site-packages\numpy\lib\stride_tricks.py in _broadcast_to(array, shape, subok, readonly)
126 broadcast = np.nditer(
127 (array,), flags=['multi_index', 'refs_ok', 'zerosize_ok'] + extras,
--> 128 op_flags=[op_flag], itershape=shape, order='C').itviews[0]
129 result = _maybe_view_as_subclass(array, broadcast)
130 if needs_writeable and not result.flags.writeable:
ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (1,4) and requested shape (4,3)
注意 - 此功能可用于 1.10.0 及以后的版本。
该函数接受以下参数。
numpy.broadcast_to(array, shape, subok)
Help on function broadcast_to in module numpy.lib.stride_tricks:
broadcast_to(array, shape, subok=False)
Broadcast an array to a new shape.
Parameters
----------
array : array_like
The array to broadcast.
shape : tuple
The shape of the desired array.
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise
the returned array will be forced to be a base-class array (default).
Returns