pola-rs/polars · error
{key}
Error message
{key} What it means
Indexing a Categories object with a string looks up the category by name; if the name is not present, a plain KeyError with the key as its message is raised. This is standard mapping-style behavior for missing keys.
Solutions
- Check membership first with `key in categories`
- Wrap the lookup in try/except KeyError
- Verify you are using the Categories instance that actually backs your column
Example fix
// before cat = categories['setosa '] // after cat = categories['setosa'] if 'setosa' in categories else None
Defensive patterns
Strategy: validation
Validate before calling
if key not in categories:
key = key.strip() # or handle missing before lookup
cat = categories[key] Type guard
def has_category(categories, key: str) -> bool:
return isinstance(key, str) and key in categories Try / catch
try:
cat = categories[name]
except KeyError:
cat = None # or log and skip Prevention
- Check `in` membership before string lookups
- Normalize/trim category strings consistently
- Ensure you use the Categories instance from the same dataset/namespace
When it happens
Trigger: categories['nonexistent_string'] where the string is not a registered category; typos in category names; querying a Categories instance from a different namespace/table than the data.
Common situations: Looking up a category that was filtered out or dropped; case-sensitivity mistakes ('A' vs 'a'); cross-dataset category reuse.
Understand the failure class
Background: 'Could not be found', 'does not exist', 'not found in database': the resource-not-found family when an ID, slug, key, or URI lookup comes back empty — this error's family across 20 libraries.
Related errors
- activate dtype-categorical to convert dictionary arrays
- can not get dtype of Categorical AnyValue
- Categorical physical must be one of pl.UInt(8|16|32)
- category index out of range
- comparing categoricals with different Categories is not…
AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18).
Data as JSON: /api/errors/f553d6465b45bbaa.
Report an issue: GitHub.
Appendix: source
Thrown at py-polars/src/polars/datatypes/classes.py:846
phys = self._categories.physical()
if phys == "u8":
return pldt.UInt8
elif phys == "u16":
return pldt.UInt16
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
View on GitHub (pinned to fe841f959e)