pola-rs/polars · error · TypeError
cannot select columns using NumPy array of type {key.dtype}
Error message
cannot select columns using NumPy array of type {key.dtype} What it means
For NumPy-array keys on a DataFrame, polars selects columns by dtype kind: 'i'/'u' → positions, 'b' → mask, or by name when key[0] is a str. Float arrays, object arrays whose first element is not a string, and exotic dtypes (complex, datetime64) fall through to this TypeError.
Source
Thrown at py-polars/src/polars/_utils/getitem.py:255
if key.ndim == 0:
key = np.atleast_1d(key)
elif key.ndim != 1:
msg = "multi-dimensional NumPy arrays not supported as index"
raise TypeError(msg)
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]View on GitHub (pinned to df599052da)
Solutions
- Cast the array: key.astype("int64") for positions or key.astype("str") for names.
- Prefer df.select("a", "b") / df.select(pl.col(names)) for name-based selection.
- Validate key.dtype.kind in ('i', 'u', 'b') before indexing in generic code.
Example fix
// before
cols = df[np.array([0.0, 2.0])]
// after
cols = df[np.array([0, 2])]
// or: cols = df[np.array([0.0, 2.0]).astype("int64")] Defensive patterns
Strategy: type-guard
Validate before calling
key = np.asarray(key)
if key.dtype.kind not in ("i", "u", "b"):
if key.dtype.kind == "f" and np.all(key == np.floor(key)):
key = key.astype("int64")
elif key.size and isinstance(key[0], str):
key = key.astype("str")
else:
raise TypeError(f"NumPy key dtype {key.dtype} cannot select columns")
out = df[key] Type guard
def is_column_select_ndarray(key: np.ndarray) -> bool:
return key.dtype.kind in ("i", "u", "b") or (key.size > 0 and isinstance(key[0], str)) Try / catch
try:
out = df[key]
except TypeError as e:
if "cannot select columns using NumPy array of type" in str(e):
out = df[np.asarray(key).astype("int64")]
else:
raise Prevention
- Cast index arrays to int64 at creation: np.arange(..., dtype=int).
- Avoid object arrays of mixed types as column keys.
- Use df.select(*names) for string-based selection instead of object ndarrays.
When it happens
Trigger: df[np.array([0.0, 1.0])]; df[np.array(["a", 1], dtype=object)]; df[np.array([1 + 0j])]; float indices from np.linspace or pandas float Index.values.
Common situations: Index arrays defaulting to float64 after arithmetic; mixed-type object arrays from lists of heterogeneous JSON values; numpy datetime64 arrays mistakenly used as column keys.
Related errors
- cannot select columns using Series of type {dtype}
- cannot create DataFrame from zero-dimensional array
- cannot create DataFrame from array with more than two dimens
- dimensions of `schema` ({n_schema_cols}) must match data dim
- cannot select columns using Sequence with elements of type {
AI-assisted analysis of pola-rs/polars@df599052da (2026-08-16).
Data as JSON: /api/errors/03809872c1ab6b7c.
Report an issue: GitHub.