Skip to content

unique_counts

Returns the unique elements of an input array x, and the corresponding counts for each unique element in 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 namedtuple

The result containing: * values - The unique elements of an input array. * counts - The corresponding counts for each unique element.

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_counts(x)
UniqueCountsResult(values=array([-3,  0,  1,  2]), counts=array([1, 1, 2, 2]))
Source code in sparse/numba_backend/_coo/common.py
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
def unique_counts(x, /):
    """
    Returns the unique elements of an input array `x`, and the corresponding
    counts for each unique element in `x`.

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

    Returns
    -------
    out : namedtuple
        The result containing:
        * values - The unique elements of an input array.
        * counts - The corresponding counts for each unique element.

    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_counts(x)
    UniqueCountsResult(values=array([-3,  0,  1,  2]), counts=array([1, 1, 2, 2]))
    """

    x = _validate_coo_input(x)

    x = x.flatten()
    values, counts = np.unique(x.data, return_counts=True)
    if x.nnz < x.size:
        values = np.concatenate([[x.fill_value], values])
        counts = np.concatenate([[x.size - x.nnz], counts])
        sorted_indices = np.argsort(values)
        values[sorted_indices] = values.copy()
        counts[sorted_indices] = counts.copy()

    return UniqueCountsResult(values, counts)