{"record":{"id":"03809872c1ab6b7c","repo":"pola-rs/polars","slug":"cannot-select-columns-using-numpy-array-of-type-k","errorCode":null,"errorMessage":"cannot select columns using NumPy array of type {key.dtype}","messagePattern":"cannot select columns using NumPy array of type (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/_utils/getitem.py","lineNumber":255,"sourceCode":"        if key.ndim == 0:\n            key = np.atleast_1d(key)\n        elif key.ndim != 1:\n            msg = \"multi-dimensional NumPy arrays not supported as index\"\n            raise TypeError(msg)\n\n        if len(key) == 0:\n            return df.__class__()\n\n        dtype_kind = key.dtype.kind\n        if dtype_kind in (\"i\", \"u\"):\n            return _select_columns_by_index(df, key)\n        elif dtype_kind == \"b\":\n            return _select_columns_by_mask(df, key)\n        elif isinstance(key[0], str):\n            return _select_columns_by_name(df, key)\n        else:\n            msg = f\"cannot select columns using NumPy array of type {key.dtype}\"\n            raise TypeError(msg)\n\n    msg = (\n        f\"cannot select columns using key of type {qualified_type_name(key)!r}: {key!r}\"\n    )\n    raise TypeError(msg)\n\n\ndef _select_columns_by_index(df: DataFrame, key: Iterable[int]) -> DataFrame:\n    series = [df.to_series(i) for i in key]\n    return df.__class__(series)\n\n\ndef _select_columns_by_name(df: DataFrame, key: Iterable[str]) -> DataFrame:\n    return df._from_pydf(df._df.select(list(key)))\n\n\ndef _select_columns_by_mask(\n    df: DataFrame, key: Sequence[bool] | Series | np.ndarray[Any, Any]","sourceCodeStart":237,"sourceCodeEnd":273,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/_utils/getitem.py#L237-L273","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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."],"exampleFix":"// before\ncols = df[np.array([0.0, 2.0])]\n\n// after\ncols = df[np.array([0, 2])]\n// or: cols = df[np.array([0.0, 2.0]).astype(\"int64\")]","handlingStrategy":"type-guard","validationCode":"key = np.asarray(key)\nif key.dtype.kind not in (\"i\", \"u\", \"b\"):\n    if key.dtype.kind == \"f\" and np.all(key == np.floor(key)):\n        key = key.astype(\"int64\")\n    elif key.size and isinstance(key[0], str):\n        key = key.astype(\"str\")\n    else:\n        raise TypeError(f\"NumPy key dtype {key.dtype} cannot select columns\")\nout = df[key]","typeGuard":"def is_column_select_ndarray(key: np.ndarray) -> bool:\n    return key.dtype.kind in (\"i\", \"u\", \"b\") or (key.size > 0 and isinstance(key[0], str))","tryCatchPattern":"try:\n    out = df[key]\nexcept TypeError as e:\n    if \"cannot select columns using NumPy array of type\" in str(e):\n        out = df[np.asarray(key).astype(\"int64\")]\n    else:\n        raise","preventionTips":["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."],"tags":["numpy","dataframe","dtype","column-selection"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}