pola-rs/polars · error · TypeError
cannot select elements using key of type {qualified_type_nam
Error message
cannot select elements using key of type {qualified_type_name(key)!r}: {key!r} What it means
This is the terminal fallback of Series.__getitem__: the key matched none of the supported types (int, slice, Sequence, pl.Series, NumPy ndarray). Keys like a bare float, dict, or arbitrary object reach this branch and raise TypeError with the key's type and repr.
Source
Thrown at py-polars/src/polars/_utils/getitem.py:90
try:
indices = pl.Series("", key, dtype=Int64)
except TypeError:
msg = f"cannot select elements using Sequence with elements of type {qualified_type_name(first)!r}"
raise TypeError(msg) from None
indices = _convert_series_to_indices(indices, s.len())
return _select_elements_by_index(s, indices)
elif isinstance(key, pl.Series):
indices = _convert_series_to_indices(key, s.len())
return _select_elements_by_index(s, indices)
elif _check_for_numpy(key) and isinstance(key, np.ndarray):
indices = _convert_np_ndarray_to_indices(key, s.len())
return _select_elements_by_index(s, indices)
msg = f"cannot select elements using key of type {qualified_type_name(key)!r}: {key!r}"
raise TypeError(msg)
def _select_elements_by_slice(s: Series, key: slice) -> Series:
return PolarsSlice(s).apply(key) # type: ignore[return-value]
def _select_elements_by_index(s: Series, key: Series) -> Series:
return s._from_pyseries(s._s.gather_with_series(key._s))
# `str` overlaps with `Sequence[str]`
# We can ignore this but we must keep this overload ordering
@overload
def get_df_item_by_key(
df: DataFrame, key: tuple[SingleIndexSelector, SingleColSelector]
) -> Any: ...
View on GitHub (pinned to df599052da)
Solutions
- Convert integral floats: s[int(key)].
- Wrap multiple values into a list, pl.Series, or np.array before indexing.
- For Boolean selection pass a list/Series of bools, not a dict or object.
Example fix
// before i = positions.mean() # float val = s[i] // after val = s[int(positions.mean())]
Defensive patterns
Strategy: type-guard
Validate before calling
def normalize_series_key(key):
if isinstance(key, float) and key.is_integer():
return int(key)
if isinstance(key, (list, tuple, pl.Series)) or isinstance(key, slice) or isinstance(key, int):
return key
raise TypeError(f"unsupported Series key type: {type(key).__name__}")
val = s[normalize_series_key(key)] Type guard
def is_supported_series_key(key: object) -> bool:
return isinstance(key, (int, slice, list, tuple, pl.Series)) or (
_check_numpy(key) and isinstance(key, __import__("numpy").ndarray)
) Try / catch
try:
val = s[key]
except TypeError as e:
if "cannot select elements using key of type" in str(e):
raise TypeError(f"bad index {key!r}; pass int, slice, list[int], Series, or ndarray") from e
raise Prevention
- Convert computed float indices with int(...) before indexing.
- Validate external keys (JSON/config) against the supported key set.
- Keep indexing helpers that always return normalized keys.
When it happens
Trigger: s[1.0]; s[{"a": 1}]; s[some_custom_object]; a numpy scalar that is neither int-subclass nor ndarray slipping through.
Common situations: Dict keys or JSON numbers flowing into indexing code; floats from computed indices not rounded to int; passing a mapping where a key or list was intended.
Related errors
- cannot select elements using Sequence with elements of type
- cannot use Series of dtype {key.dtype!r} for indexing; expec
- cannot use "{key!r}" for indexing
- unsupported type {qualified_type_name(arg)!r} for {arg!r}
- passing Expr objects to the DataFrame constructor is not sup
AI-assisted analysis of pola-rs/polars@df599052da (2026-08-16).
Data as JSON: /api/errors/eb63ed325abdf609.
Report an issue: GitHub.