跳到内容

clip

裁剪(限制)数组中的值。

返回一个值被限制在 [min, max] 范围内的数组。必须提供 min 或 max 中的一个。

参数

名称 类型 描述 默认值
a
必需
min 标量或 `SparseArray` 或 `None`

最小值。如果为 None,则不对下边界进行裁剪。

None
max 标量或 `SparseArray` 或 `None`

最大值。如果为 None,则不对上边界进行裁剪。

None
out SparseArray

如果提供,结果将放入此数组中。它可以是用于就地裁剪的输入数组。out 必须具有正确的形状以容纳输出。其类型会被保留。

None

返回值

名称 类型 描述
clipped_array SparseArray

一个数组,其元素来自 self,但其中值小于 min 的被替换为 min,值大于 max 的被替换为 max

示例

>>> import sparse
>>> x = sparse.COO.from_numpy([0, 0, 0, 1, 2, 3])
>>> sparse.clip(x, min=1).todense()
array([1, 1, 1, 1, 2, 3])
>>> sparse.clip(x, max=1).todense()
array([0, 0, 0, 1, 1, 1])
>>> sparse.clip(x, min=1, max=2).todense()
array([1, 1, 1, 1, 2, 2])
另请参阅

numpy.clip : 等效的 NumPy 函数

源代码位于 sparse/numba_backend/_coo/common.py
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
def clip(a, min=None, max=None, out=None):
    """
    Clip (limit) the values in the array.

    Return an array whose values are limited to ``[min, max]``. One of min
    or max must be given.

    Parameters
    ----------
    a
    min : scalar or `SparseArray` or `None`
        Minimum value. If `None`, clipping is not performed on lower
        interval edge.
    max : scalar or `SparseArray` or `None`
        Maximum value. If `None`, clipping is not performed on upper
        interval edge.
    out : SparseArray, optional
        If provided, the results will be placed in this array. It may be
        the input array for in-place clipping. `out` must be of the right
        shape to hold the output. Its type is preserved.

    Returns
    -------
    clipped_array : SparseArray
        An array with the elements of `self`, but where values < `min` are
        replaced with `min`, and those > `max` with `max`.

    Examples
    --------
    >>> import sparse
    >>> x = sparse.COO.from_numpy([0, 0, 0, 1, 2, 3])
    >>> sparse.clip(x, min=1).todense()  # doctest: +NORMALIZE_WHITESPACE
    array([1, 1, 1, 1, 2, 3])
    >>> sparse.clip(x, max=1).todense()  # doctest: +NORMALIZE_WHITESPACE
    array([0, 0, 0, 1, 1, 1])
    >>> sparse.clip(x, min=1, max=2).todense()  # doctest: +NORMALIZE_WHITESPACE
    array([1, 1, 1, 1, 2, 2])

    See Also
    --------
    numpy.clip : Equivalent NumPy function
    """
    a = asCOO(a, name="clip")
    return a.clip(min, max)