跳到内容

唯一值

返回输入数组 x 中的唯一元素。

参数

名称 类型 描述 默认值
x COO

输入 COO 数组。如果它不是一维的,将被展平。

必需

返回值

名称 类型 描述
输出 ndarray

输入数组中的唯一元素。

引发

类型 描述
ValueError

如果输入数组的格式与 COO 不同。

示例

>>> import sparse
>>> x = sparse.COO.from_numpy([1, 0, 2, 1, 2, -3])
>>> sparse.unique_values(x)
array([-3,  0,  1,  2])
源代码位于 sparse/numba_backend/_coo/common.py
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
def unique_values(x, /):
    """
    Returns the unique elements of an input array `x`.

    Parameters
    ----------
    x : COO
        Input COO array. It will be flattened if it is not already 1-D.

    Returns
    -------
    out : ndarray
        The unique elements of an input array.

    Raises
    ------
    ValueError
        If the input array is in a different format than COO.

    Examples
    --------
    >>> import sparse
    >>> x = sparse.COO.from_numpy([1, 0, 2, 1, 2, -3])
    >>> sparse.unique_values(x)
    array([-3,  0,  1,  2])
    """

    x = _validate_coo_input(x)

    x = x.flatten()
    values = np.unique(x.data)
    if x.nnz < x.size:
        values = np.sort(np.concatenate([[x.fill_value], values]))
    return values