跳到内容

reshape

重塑数组,同时不改变其数据。

参数

名称 类型 描述 默认值
x

要重塑的输入数组。

必需
shape

与原始形状兼容的新形状。允许一个形状维度为-1。当形状维度为-1时,相应的输出数组形状维度必须从数组的长度和剩余维度推断。

必需
copy

是否复制输入数组。如果为True,函数总是复制。如果为False,函数绝不复制。如果为None,函数尽可能避免复制。默认值:None

None

返回值

名称 类型 描述
out 数组

一个与x具有相同数据类型和元素的输出数组。

引发

类型 描述
ValueError

如果copy=False且需要复制,则会引发ValueError

示例

>>> a = sparse.COO.from_numpy(np.array([[0, 1], [2, 0]]))
>>> o = sparse.reshape(a, shape=(1, 4))
>>> o.todense()
array([[0, 1, 2, 0]])
源代码位于 sparse/numba_backend/_common.py
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
def reshape(x, /, shape, *, copy=None):
    """
    Reshapes an array without changing its data.

    Parameters
    ----------
    x: array
        input array to reshape.
    shape: Tuple[int, ...]
        a new shape compatible with the original shape. One shape dimension is allowed to be ``-1``.
        When a shape dimension is ``-1``, the corresponding output array shape dimension must be inferred
        from the length of the array and the remaining dimensions.
    copy: Optional[bool]
        whether or not to copy the input array.
        If ``True``, the function always copies.
        If ``False``, the function must never copies.
        If ``None``, the function avoids copying, if possible.
        Default: ``None``.

    Returns
    -------
    out: array
        an output array having the same data type and elements as ``x``.

    Raises
    ------
    ValueError
        If ``copy=False`` and a copy would be necessary, a ``ValueError``
        will be raised.

    Examples
    --------
    >>> a = sparse.COO.from_numpy(np.array([[0, 1], [2, 0]]))
    >>> o = sparse.reshape(a, shape=(1, 4))
    >>> o.todense()
    array([[0, 1, 2, 0]])
    """
    return x.reshape(shape=shape)