{"record":{"id":"a78f807c11c4ab02","repo":"pola-rs/polars","slug":"cannot-select-columns-using-key-of-type-qualified","errorCode":null,"errorMessage":"cannot select columns using key of type {qualified_type_name(key)!r}: {key!r}","messagePattern":"cannot select columns using key of type (.+?): (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/_utils/getitem.py","lineNumber":260,"sourceCode":"\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]\n) -> DataFrame:\n    if len(key) != df.width:\n        msg = f\"expected {df.width} values when selecting columns by boolean mask, got {len(key)}\"\n        raise ValueError(msg)\n","sourceCodeStart":242,"sourceCodeEnd":278,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/_utils/getitem.py#L242-L278","documentation":"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.","triggerScenarios":"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].","commonSituations":"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.","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)]"],"exampleFix":"# before\ncols = {\"a\", \"b\"}   # set is not a Sequence -> TypeError\ndf[:, cols]\n\n# after\ndf[:, sorted(cols)]  # list of column names","handlingStrategy":"type-guard","validationCode":"from collections.abc import Sequence\nimport polars as pl\n\ntry:\n    import numpy as np\n    _ND = (np.ndarray,)\nexcept ImportError:\n    _ND = ()\n\nallowed = (int, str, slice, range, Sequence, pl.Series) + _ND\nif not isinstance(col_key, allowed):\n    raise TypeError(f\"unsupported column key: {type(col_key).__name__}\")","typeGuard":"from collections.abc import Sequence\nimport polars as pl\n\ndef is_valid_column_key(key: object) -> bool:\n    try:\n        import numpy as np\n        nd = isinstance(key, np.ndarray)\n    except ImportError:\n        nd = False\n    return isinstance(key, (int, str, slice, range, Sequence, pl.Series)) or nd","tryCatchPattern":null,"preventionTips":["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"],"tags":["python","polars","dataframe","getitem","column-selection","typeerror"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}