跳到内容

broadcast_to

将数组广播到指定形状。

参数

名称 类型 描述 默认值
x

要广播的数组。

必需
shape

数组形状。必须与 x 兼容。如果数组与指定形状不兼容,函数将引发异常。

必需

返回值

名称 类型 描述
out 数组

一个具有指定形状且数据类型与 x 相同的数组。

示例

>>> a = sparse.COO.from_numpy(np.array([[0, 1], [2, 0]]))
>>> o = sparse.broadcast_to(a, shape=(1, 2, 2))
>>> o.todense()
array([[[0, 1],
        [2, 0]]])
源代码位于 sparse/numba_backend/_common.py
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
@_support_numpy
def broadcast_to(x, /, shape):
    """
    Broadcasts an array to a specified shape.

    Parameters
    ----------
    x: array
        array to broadcast.
    shape: Tuple[int, ...]
        array shape. Must be compatible with ``x``.
        If the array is incompatible with the specified shape, the function raises an exception.

    Returns
    -------
    out: array
        an array having a specified shape and having the same data type as ``x``.

    Examples
    --------
    >>> a = sparse.COO.from_numpy(np.array([[0, 1], [2, 0]]))
    >>> o = sparse.broadcast_to(a, shape=(1, 2, 2))
    >>> o.todense()  # doctest: +NORMALIZE_WHITESPACE
    array([[[0, 1],
            [2, 0]]])
    """
    return x.broadcast_to(shape)