pola-rs/polars · error
cannot select columns using NumPy array of type
Error message
cannot select columns using NumPy array of type {key.dtype} What it means
Raised by Polars when a NumPy array is used to select columns of a DataFrame but its dtype is not one of the supported selection kinds (integer, boolean, or string elements). Polars dispatches column selection based on the array's dtype_kind and throws this TypeError for any other dtype (e.g. float, datetime, object holding non-strings).
Solutions
- Cast the array to integers before selecting: df[:, np.array([0.0, 2.0]).astype(int)]
- If it is meant to be a boolean mask, cast to bool: df[:, arr.astype(bool)]
- If selecting by name, ensure the array is a proper string dtype (arr.astype(str)) or convert to a Python list of str: df[:, arr.tolist()]
Example fix
// before df[:, np.array([0.0, 1.0])] # float array -> TypeError // after df[:, np.array([0.0, 1.0]).astype(int)]
Defensive patterns
Strategy: validation
Validate before calling
import numpy as np
if isinstance(key, np.ndarray) and key.ndim == 1:
if key.dtype.kind == "i":
pass # positional column selection OK
elif key.dtype.kind == "b":
assert len(key) == df.width, "mask must match df.width"
elif key.dtype.kind in {"U", "S", "O"} and all(isinstance(v, str) for v in key):
key = key.astype(str) # name selection OK
else:
key = key.astype(int if key.dtype.kind == "f" else str)
df[:, key] Type guard
def is_valid_column_np_key(key) -> bool:
import numpy as np
return isinstance(key, np.ndarray) and key.ndim == 1 and key.dtype.kind in ("i", "u", "b") or (
isinstance(key, np.ndarray) and all(isinstance(v, str) for v in key)
) Prevention
- Compute column positions with integer arithmetic (//, astype(int)), never float
- Cast np.where results with .astype(bool) before using as a mask
- Convert arrays of names to Python lists of str via .tolist()
When it happens
Trigger: df[np.array([0.0, 2.0])] — a float or otherwise unsupported NumPy array passed to __getitem__ along the column axis, e.g. df[:, np.array([0.5, 1.5])] or df[np.array(['a'], dtype=object) mixed with non-str elements].
Common situations: Selecting columns with positions computed by floating-point arithmetic (mean, division) instead of casting to int; building a mask via np.where without converting to bool; a stale array that ended up float after NaN insertion.
Related errors
- cannot create DataFrame from array with more than two…
- cannot select columns using key of type
- cannot select rows using key of type
- invalid input for `copy
- multi-dimensional NumPy arrays not supported as index
AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18).
Data as JSON: /api/errors/03809872c1ab6b7c.
Report an issue: GitHub.
Appendix: 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 fe841f959e)