unique_counts

unique_counts(x: array, /) Tuple[array, array]

Returns the unique elements of an input array x and the corresponding counts for each unique element in x.

Data-dependent output shape

The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See Data-dependent output shapes section for more details.

Note

Uniqueness should be determined based on value equality (see equal()). For input arrays having floating-point data types, value-based equality implies the following behavior.

  • As nan values compare as False, nan values should be considered distinct.

  • As complex floating-point values having at least one nan component compare as False, complex floating-point values having nan components should be considered distinct.

  • As -0 and +0 compare as True, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return -0 if -0 occurs before +0).

Each nan value and each complex floating-point value having a nan component should have a count of one, while the counts for signed zeros should be aggregated as a single count.

Parameters:

x (array) – input array. If x has more than one dimension, the function must flatten x and return the unique elements of the flattened array.

Returns:

out (Tuple[array, array]) – a namedtuple (values, counts) whose

  • first element must have the field name values and must be a one-dimensional array containing the unique elements of x. The array must have the same data type as x.

  • second element must have the field name counts and must be an array containing the number of times each unique element occurs in x. The order of the returned counts must match the order of values, such that a specific element in counts corresponds to the respective unique element in values. The returned array must have same shape as values and must have the default array index data type.

Note

The order of unique elements is not specified and may vary between implementations.

Notes

Changed in version 2022.12: Added complex data type support.

Changed in version 2023.12: Clarified flattening behavior and required the order of counts match the order of values.