{"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":null,"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/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/_utils/getitem.py#L237-L273","documentation":"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).","triggerScenarios":"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].","commonSituations":"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.","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()]"],"exampleFix":"// before\ndf[:, np.array([0.0, 1.0])]  # float array -> TypeError\n// after\ndf[:, np.array([0.0, 1.0]).astype(int)]","handlingStrategy":"validation","validationCode":"import numpy as np\nif isinstance(key, np.ndarray) and key.ndim == 1:\n    if key.dtype.kind == \"i\":\n        pass  # positional column selection OK\n    elif key.dtype.kind == \"b\":\n        assert len(key) == df.width, \"mask must match df.width\"\n    elif key.dtype.kind in {\"U\", \"S\", \"O\"} and all(isinstance(v, str) for v in key):\n        key = key.astype(str)  # name selection OK\n    else:\n        key = key.astype(int if key.dtype.kind == \"f\" else str)\ndf[:, key]","typeGuard":"def is_valid_column_np_key(key) -> bool:\n    import numpy as np\n    return isinstance(key, np.ndarray) and key.ndim == 1 and key.dtype.kind in (\"i\", \"u\", \"b\") or (\n        isinstance(key, np.ndarray) and all(isinstance(v, str) for v in key)\n    )","tryCatchPattern":null,"preventionTips":["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()"],"tags":["polars","numpy","dataframe","type-error"],"backgroundTag":"unsupported-dtype","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}