Skip to content

unique_values

Returns the unique elements of an input array x.

Parameters:

Name Type Description Default
x COO

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

required

Returns:

Name Type Description
out ndarray

The unique elements of an input array.

Raises:

Type Description
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])
Source code in sparse/numba_backend/_coo/common.py
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
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, equal_nan=False)
    fill_count = x.size - x.nnz
    if fill_count > 0:
        if np.isnan(x.fill_value):
            # Per the Array API spec, NaNs compare as False, so each NaN is distinct.
            values = np.concatenate([values, np.full(fill_count, x.fill_value)])
        else:
            values = np.sort(np.concatenate([[x.fill_value], values]))
    return values