跳到内容

填充

执行相当于sparse.SparseArray。请注意,此函数返回一个新数组而不是视图。

参数

名称 类型 描述 默认值
数组 SparseArray

待填充的稀疏数组。

必需
pad_width (sequence, array_like, int)

填充到每个轴边缘的值数量。((before_1, after_1), … (before_N, after_N)) 表示每个轴的唯一填充宽度。((before, after),) 表示每个轴的前后填充宽度相同。(pad,) 或 int 是所有轴的前后填充宽度都等于填充宽度的快捷方式。

sequence
mode str

填充为常数值,即填充值。目前仅实现了常量模式。

'constant'
constant_values int

用于设置每个轴的填充值。默认值为 0。此值必须与填充值相同。

必需

返回值

类型 描述
SparseArray

填充后的稀疏数组。

引发

类型 描述
NotImplementedError

如果 mode != 'constant' 或存在未知参数。

ValueError

如果 constant_values != self.fill_value

另请参阅

numpy.pad : NumPy 等效函数

源代码位于 sparse/numba_backend/_common.py
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
def pad(array, pad_width, mode="constant", **kwargs):
    """
    Performs the equivalent of [`sparse.SparseArray`][]. Note that
    this function returns a new array instead of a view.

    Parameters
    ----------
    array : SparseArray
        Sparse array which is to be padded.

    pad_width : {sequence, array_like, int}
        Number of values padded to the edges of each axis. ((before_1, after_1), … (before_N, after_N)) unique pad
        widths for each axis. ((before, after),) yields same before and after pad for each axis. (pad,) or int is a
        shortcut for before = after = pad width for all axes.

    mode : str
        Pads to a constant value which is fill value. Currently only constant mode is implemented

    constant_values : int
        The values to set the padded values for each axis. Default is 0. This must be same as fill value.

    Returns
    -------
    SparseArray
        The padded sparse array.

    Raises
    ------
    NotImplementedError
        If mode != 'constant' or there are unknown arguments.

    ValueError
        If constant_values != self.fill_value

    See Also
    --------
    [`numpy.pad`][] : NumPy equivalent function

    """
    if not isinstance(array, SparseArray):
        raise NotImplementedError("Input array is not compatible.")

    if mode.lower() != "constant":
        raise NotImplementedError(f"Mode '{mode}' is not yet supported.")

    if not equivalent(kwargs.pop("constant_values", _zero_of_dtype(array.dtype)), array.fill_value):
        raise ValueError("constant_values can only be equal to fill value.")

    if kwargs:
        raise NotImplementedError("Additional Unknown arguments present.")

    from ._coo import COO

    array = array.asformat("coo")

    pad_width = np.broadcast_to(pad_width, (len(array.shape), 2))
    new_coords = array.coords + pad_width[:, 0:1]
    new_shape = tuple([array.shape[i] + pad_width[i, 0] + pad_width[i, 1] for i in range(len(array.shape))])
    new_data = array.data
    return COO(new_coords, new_data, new_shape, fill_value=array.fill_value)