{"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":null,"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/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/_utils/getitem.py#L242-L278","documentation":"Raised by Polars when the key passed to column selection is of a type that cannot be interpreted as column indices, a boolean mask, or column names. It is the fallback TypeError in _select_columns after all known key kinds (int, list, slice, Series, NumPy array of int/bool/str) have been ruled out.","triggerScenarios":"df[{'a': 1}] (dict), df[0.5] (float), df[(lambda x: x)] — any non-supported key type passed where columns are selected, e.g. df[my_tuple_of_floats].","commonSituations":"Accidentally passing a dict (intending to assign/rename) via __getitem__; passing a float column position instead of int; passing a set (unordered) of labels; migrating pandas code where a tuple key had different semantics.","solutions":["Use an int for a single position, a list of ints for multiple positions, a list of str for names, or a bool mask/Series","Convert the key to a supported form first, e.g. df[list(key)] for a set/tuple of labels or df[int(key)] for a float index","If you meant to create columns, use df.with_columns(...) or assignment instead of df[key]"],"exampleFix":"// before\ndf[{\"a\": 1}]  # dict key -> TypeError\n// after\ndf.select(\"a\")  # or df[\"a\"] for one column","handlingStrategy":"type-guard","validationCode":"SUPPORTED = (int, slice, list, tuple, range, pl.Series)\nassert isinstance(key, SUPPORTED), f\"unsupported column key type: {type(key)}\"","typeGuard":"def is_valid_column_key(key) -> bool:\n    import polars as pl\n    if isinstance(key, (int, slice, range, pl.Series)):\n        return True\n    if isinstance(key, (list, tuple)):\n        return all(isinstance(v, (int, str, bool)) for v in key)\n    try:\n        import numpy as np\n        return isinstance(key, np.ndarray) and key.dtype.kind in (\"i\", \"u\", \"b\", \"U\")\n    except ImportError:\n        return False","tryCatchPattern":"try:\n    out = df[key]\nexcept TypeError as e:\n    if \"cannot select columns\" in str(e):\n        out = df[list(key)] if hasattr(key, \"__iter__\") else df.select(str(key))\n    else:\n        raise","preventionTips":["Never pass dicts, sets, or floats as DataFrame __getitem__ keys","Use explicit df.select(...)/df[:, ...] to make intent clear","When migrating pandas code, replace tuple/dict keys with select/filter calls"],"tags":["polars","dataframe","type-error","invalid-key"],"backgroundTag":"invalid-argument-value","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"}