{"record":{"id":"eb63ed325abdf609","repo":"pola-rs/polars","slug":"cannot-select-elements-using-key-of-type-qualifie","errorCode":null,"errorMessage":"cannot select elements using key of type {qualified_type_name(key)!r}: {key!r}","messagePattern":"cannot select elements using key of type (.+?): (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/_utils/getitem.py","lineNumber":90,"sourceCode":"        try:\n            indices = pl.Series(\"\", key, dtype=Int64)\n        except TypeError:\n            msg = f\"cannot select elements using Sequence with elements of type {qualified_type_name(first)!r}\"\n            raise TypeError(msg) from None\n\n        indices = _convert_series_to_indices(indices, s.len())\n        return _select_elements_by_index(s, indices)\n\n    elif isinstance(key, pl.Series):\n        indices = _convert_series_to_indices(key, s.len())\n        return _select_elements_by_index(s, indices)\n\n    elif _check_for_numpy(key) and isinstance(key, np.ndarray):\n        indices = _convert_np_ndarray_to_indices(key, s.len())\n        return _select_elements_by_index(s, indices)\n\n    msg = f\"cannot select elements using key of type {qualified_type_name(key)!r}: {key!r}\"\n    raise TypeError(msg)\n\n\ndef _select_elements_by_slice(s: Series, key: slice) -> Series:\n    return PolarsSlice(s).apply(key)  # type: ignore[return-value]\n\n\ndef _select_elements_by_index(s: Series, key: Series) -> Series:\n    return s._from_pyseries(s._s.gather_with_series(key._s))\n\n\n# `str` overlaps with `Sequence[str]`\n# We can ignore this but we must keep this overload ordering\n@overload\ndef get_df_item_by_key(\n    df: DataFrame, key: tuple[SingleIndexSelector, SingleColSelector]\n) -> Any: ...\n\n","sourceCodeStart":72,"sourceCodeEnd":108,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/_utils/getitem.py#L72-L108","documentation":"This is the terminal fallback of Series.__getitem__: the key matched none of the supported types (int, slice, Sequence, pl.Series, NumPy ndarray). Keys like a bare float, dict, or arbitrary object reach this branch and raise TypeError with the key's type and repr.","triggerScenarios":"s[1.0]; s[{\"a\": 1}]; s[some_custom_object]; a numpy scalar that is neither int-subclass nor ndarray slipping through.","commonSituations":"Dict keys or JSON numbers flowing into indexing code; floats from computed indices not rounded to int; passing a mapping where a key or list was intended.","solutions":["Convert integral floats: s[int(key)].","Wrap multiple values into a list, pl.Series, or np.array before indexing.","For Boolean selection pass a list/Series of bools, not a dict or object."],"exampleFix":"// before\ni = positions.mean()  # float\nval = s[i]\n\n// after\nval = s[int(positions.mean())]","handlingStrategy":"type-guard","validationCode":"def normalize_series_key(key):\n    if isinstance(key, float) and key.is_integer():\n        return int(key)\n    if isinstance(key, (list, tuple, pl.Series)) or isinstance(key, slice) or isinstance(key, int):\n        return key\n    raise TypeError(f\"unsupported Series key type: {type(key).__name__}\")\n\nval = s[normalize_series_key(key)]","typeGuard":"def is_supported_series_key(key: object) -> bool:\n    return isinstance(key, (int, slice, list, tuple, pl.Series)) or (\n        _check_numpy(key) and isinstance(key, __import__(\"numpy\").ndarray)\n    )","tryCatchPattern":"try:\n    val = s[key]\nexcept TypeError as e:\n    if \"cannot select elements using key of type\" in str(e):\n        raise TypeError(f\"bad index {key!r}; pass int, slice, list[int], Series, or ndarray\") from e\n    raise","preventionTips":["Convert computed float indices with int(...) before indexing.","Validate external keys (JSON/config) against the supported key set.","Keep indexing helpers that always return normalized keys."],"tags":["series","getitem","type-error","indexing"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}