pola-rs/polars · error · TypeError
cannot select columns using key of type {qualified_type_name
Error message
cannot select columns using key of type {qualified_type_name(key)!r}: {key!r} What it means
Raised by the column-selector branch of DataFrame.__getitem__ (polars/_utils/getitem.py:260). When selecting with df[cols] or the second slot of df[rows, cols], polars accepts int, str, slice, range, a Sequence of str/int/bool, pl.Series, and 1D numpy arrays; any other key type falls through to this TypeError naming the offending type. For a single unknown key, polars first tries row selection and, on TypeError, retries as columns, so this message is what surfaces for keys unknown to both branches.
Source
Thrown at py-polars/src/polars/_utils/getitem.py:260
if len(key) == 0:
return df.__class__()
dtype_kind = key.dtype.kind
if dtype_kind in ("i", "u"):
return _select_columns_by_index(df, key)
elif dtype_kind == "b":
return _select_columns_by_mask(df, key)
elif isinstance(key[0], str):
return _select_columns_by_name(df, key)
else:
msg = f"cannot select columns using NumPy array of type {key.dtype}"
raise TypeError(msg)
msg = (
f"cannot select columns using key of type {qualified_type_name(key)!r}: {key!r}"
)
raise TypeError(msg)
def _select_columns_by_index(df: DataFrame, key: Iterable[int]) -> DataFrame:
series = [df.to_series(i) for i in key]
return df.__class__(series)
def _select_columns_by_name(df: DataFrame, key: Iterable[str]) -> DataFrame:
return df._from_pydf(df._df.select(list(key)))
def _select_columns_by_mask(
df: DataFrame, key: Sequence[bool] | Series | np.ndarray[Any, Any]
) -> DataFrame:
if len(key) != df.width:
msg = f"expected {df.width} values when selecting columns by boolean mask, got {len(key)}"
raise ValueError(msg)
View on GitHub (pinned to df599052da)
Solutions
- Convert the key to a list of column names: df[:, sorted({'a', 'b'})] or df[:, list(names)]
- Normalize numpy scalars to Python int: df[:, int(idx)]
- Prefer the explicit API: df.select('a', 'b') or df.get_column('a')
- Unpack generators: df[:, list(gen)]
Example fix
# before
cols = {"a", "b"} # set is not a Sequence -> TypeError
df[:, cols]
# after
df[:, sorted(cols)] # list of column names Defensive patterns
Strategy: type-guard
Validate before calling
from collections.abc import Sequence
import polars as pl
try:
import numpy as np
_ND = (np.ndarray,)
except ImportError:
_ND = ()
allowed = (int, str, slice, range, Sequence, pl.Series) + _ND
if not isinstance(col_key, allowed):
raise TypeError(f"unsupported column key: {type(col_key).__name__}") Type guard
from collections.abc import Sequence
import polars as pl
def is_valid_column_key(key: object) -> bool:
try:
import numpy as np
nd = isinstance(key, np.ndarray)
except ImportError:
nd = False
return isinstance(key, (int, str, slice, range, Sequence, pl.Series)) or nd Prevention
- Never pass sets or generators as column selectors; convert with list()/sorted() first
- Normalize numpy scalars with int()/float-free paths before using them as indices
- Prefer df.select(...) and df.get_column(...) over __getitem__ for clarity and type checking
When it happens
Trigger: df[:, {'a', 'b']} (a set is not a Sequence); df[:, 1.5]; df[:, np.float64(2.0)] (numpy scalar is not a Python int); df[:, None]; df[:, map(str.upper, names)] (generator); df[:, some_custom_object].
Common situations: Column sets produced by set operations; numpy scalars from argmax()/argmin()/where() passed unconverted; generators from map() instead of lists; code ported from pandas label-based indexing.
Related errors
- cannot select rows using key of type {qualified_type_name(ke
- expected {df.width} values when selecting columns by boolean
- cannot select columns using Sequence with elements of type {
- index {key} is out of bounds for DataFrame of height {num_ro
- cannot treat Series of type {s.dtype} as indices
AI-assisted analysis of pola-rs/polars@df599052da (2026-08-16).
Data as JSON: /api/errors/a78f807c11c4ab02.
Report an issue: GitHub.