pola-rs/polars · error · IndexError

category index out of range

Error message

category index out of range: {key}

What it means

Indexing a Categories object with an integer converts the category index back to its string name. If the integer is not a valid category index (negative or >= number of categories), an IndexError with 'category index out of range: {key}' is raised.

Solutions

  1. Validate 0 <= idx < len(categories) before indexing
  2. Wrap in try/except IndexError
  3. Recompute the index from the current column's categories instead of reusing stored codes

Example fix

// before
name = categories[idx]  # idx=42
// after
name = categories[idx] if 0 <= idx < len(categories) else None
Defensive patterns

Strategy: validation

Validate before calling

if not (0 <= idx < len(categories)):
    raise ValueError(f'index {idx} outside 0..{len(categories)-1}')
name = categories[idx]

Type guard

def valid_index(categories, idx: int) -> bool:
    return isinstance(idx, int) and 0 <= idx < len(categories)

Try / catch

try:
    name = categories[idx]
except IndexError:
    name = None

Prevention

When it happens

Trigger: categories[42] where the categories collection has fewer than 43 entries; stale indices saved before the category mapping changed; indexing with codes from a different column/dataset.

Common situations: Persisting physical codes to disk and remapping later after categories changed; off-by-one loops over range(len)+1; sharing indices across datasets with different category sets.

Related errors


AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18). Data as JSON: /api/errors/fec7d1b40b32266e. Report an issue: GitHub.

Appendix: source

Thrown at py-polars/src/polars/datatypes/classes.py:851

        elif phys == "u32":
            return pldt.UInt32
        else:
            msg = "unknown physical dtype"
            raise RuntimeError(msg)

    def is_global(self) -> bool:
        """Returns whether this refers to the global categories."""
        return self._categories.is_global()

    def __getitem__(self, key: str | int) -> str | int:
        if isinstance(key, str):
            if (cat := self._categories.get_cat(key)) is None:
                raise KeyError(key)
            return cat
        elif isinstance(key, int):
            if (s := self._categories.cat_to_str(key)) is None:
                msg = f"category index out of range: {key}"
                raise IndexError(msg)
            return s
        else:
            msg = f"invalid key type {type(key)}; expected str or int"
            raise TypeError(msg)

    def __contains__(self, item: str | int) -> bool:
        if isinstance(item, str):
            return self._categories.get_cat(item) is not None
        elif isinstance(item, int):
            return self._categories.cat_to_str(item) is not None
        else:
            return False

    def __iter__(self) -> Iterator[str | None]:
        for i in range(self._categories.num_cats_upper_bound()):
            yield self._categories.cat_to_str(i)

    def to_series(self) -> Series:

View on GitHub (pinned to fe841f959e)