pola-rs/polars · error
cannot select rows using key of type
Error message
cannot select rows using key of type {qualified_type_name(key)!r}: {key!r} What it means
Raised by Polars when a row-selection key is of a type that is not an int, slice, range, sequence of ints, or a (NumPy-checkable) ndarray — the fallback TypeError in _select_rows. Any other key type cannot be interpreted as a row selector.
Solutions
- Use an int, slice, range, list/tuple/ndarray of ints, or a boolean mask to select rows: df[0], df[1:5], df[[0, 2]]
- Cast floats to int: df[int(2.0)] or convert sets to lists: df[sorted(key)]
- For label or condition-based selection use df.filter(expr) instead of positional keys
Example fix
// before
df[2.0] # float key -> TypeError
// after
df[2] # int
df.filter(pl.col("id") == 2) # by value Defensive patterns
Strategy: type-guard
Validate before calling
if not isinstance(key, (int, slice, range)) and not (
isinstance(key, (list, tuple)) and all(isinstance(v, int) for v in key)
):
raise TypeError(f"unsupported row key: {type(key)}") Type guard
def is_valid_row_key(key) -> bool:
import polars as pl
if isinstance(key, (int, slice, range, pl.Series)):
return True
if isinstance(key, (list, tuple)):
return all(isinstance(v, int) and not isinstance(v, bool) for v in key)
try:
import numpy as np
return isinstance(key, np.ndarray) and key.dtype.kind in ("i", "u", "b")
except ImportError:
return False Try / catch
try:
out = df[key]
except TypeError as e:
if "cannot select rows" in str(e):
out = df.filter(pl.col("id") == key) # fall back to value-based selection
else:
raise Prevention
- Cast float positions to int before row indexing
- Do not use sets, dicts, or label strings as row keys; use filter() instead
- Prefer df.filter(df["id"] == value) over positional lookups when labels are meant
When it happens
Trigger: df["row_label"] (string key goes to column selection normally, but in a row context / via getitem helpers), df[1.5] (float), df[{0}] (set), passing a custom sequence-like object not recognized as a sequence of ints, df[np.array([[0,1]])] 2-D arrays etc. depending on conversion failure.
Common situations: Copy-pasted pandas code using label-based indexing where the label is a non-int type; passing a float position like df[2.0]; passing a set of row positions; accidentally calling row selection with a dict.
Understand the failure class
Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.
Related errors
- cannot select columns using key of type
- cannot select columns using NumPy array of type
- index is out of bounds for DataFrame of height
- arr.to_struct() got a str instead of a list. hint: pass
- Array constructor is missing the required argument `shape`
AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18).
Data as JSON: /api/errors/f9024d7bcf5b62d8.
Report an issue: GitHub.
Appendix: source
Thrown at py-polars/src/polars/_utils/getitem.py:328
if not key:
return df.clear()
if isinstance(key[0], bool):
_raise_on_boolean_mask()
s = pl.Series("", key, dtype=Int64)
indices = _convert_series_to_indices(s, df.height)
return _select_rows_by_index(df, indices)
elif isinstance(key, pl.Series):
indices = _convert_series_to_indices(key, df.height)
return _select_rows_by_index(df, indices)
elif _check_for_numpy(key) and isinstance(key, np.ndarray):
indices = _convert_np_ndarray_to_indices(key, df.height)
return _select_rows_by_index(df, indices)
else:
msg = f"cannot select rows using key of type {qualified_type_name(key)!r}: {key!r}"
raise TypeError(msg)
def _select_rows_by_slice(df: DataFrame, key: slice) -> DataFrame:
return PolarsSlice(df).apply(key) # type: ignore[return-value]
def _select_rows_by_index(df: DataFrame, key: Series) -> DataFrame:
return df._from_pydf(df._df.gather_with_series(key._s))
# UTILS
def _convert_series_to_indices(s: Series, size: int) -> Series:
"""Convert a Series to indices, taking into account negative values."""
# Unsigned or signed Series (ordered from fastest to slowest).
# - pl.UInt32 (polars) or pl.UInt64 (polars_u64_idx) Series indexes.
# - Other unsigned Series indexes are converted to pl.UInt32 (polars)View on GitHub (pinned to fe841f959e)