Skip to content

build_category_map

yohou.plotting._utils.build_category_map(*series_list)

Build a sorted category-to-integer mapping from one or more series.

Parameters

Name Type Description Default
*series_list Series

One or more polars Series whose unique non-null string values are collected.

()

Returns

Name Type Description
sorted_cats list[str]

Sorted list of unique category labels.

cat_to_int dict[str, int]

Mapping from category label to integer index (0-based).

Examples

>>> import polars as pl
>>> from yohou.plotting._utils import build_category_map
>>> s = pl.Series("x", ["B", "A", "C", "A"])
>>> build_category_map(s)
(['A', 'B', 'C'], {'A': 0, 'B': 1, 'C': 2})

Source Code

Show/Hide source
def build_category_map(
    *series_list: pl.Series,
) -> tuple[list[str], dict[str, int]]:
    """Build a sorted category-to-integer mapping from one or more series.

    Parameters
    ----------
    *series_list : pl.Series
        One or more polars Series whose unique non-null string values
        are collected.

    Returns
    -------
    sorted_cats : list[str]
        Sorted list of unique category labels.
    cat_to_int : dict[str, int]
        Mapping from category label to integer index (0-based).

    Examples
    --------
    >>> import polars as pl
    >>> from yohou.plotting._utils import build_category_map
    >>> s = pl.Series("x", ["B", "A", "C", "A"])
    >>> build_category_map(s)
    (['A', 'B', 'C'], {'A': 0, 'B': 1, 'C': 2})

    """
    cats: set[str] = set()
    for s in series_list:
        cats.update(str(v) for v in s.drop_nulls().to_list())
    sorted_cats = sorted(cats)
    cat_to_int = {cat: i for i, cat in enumerate(sorted_cats)}
    return sorted_cats, cat_to_int