{"record":{"id":"98fcf4a9181b04fa","repo":"pola-rs/polars","slug":"cannot-use-key-r-for-indexing","errorCode":null,"errorMessage":"cannot use \"{key!r}\" for indexing","messagePattern":"cannot use \"(.+?)\" for indexing","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/series/series.py","lineNumber":1572,"sourceCode":"                msg = f\"cannot use Series of dtype {key.dtype!r} for indexing; expected boolean or integer dtype\"\n                raise TypeError(msg)\n\n        # TODO: implement for these types without casting to series\n        elif _check_for_numpy(key) and isinstance(key, np.ndarray):\n            if key.dtype == np.bool_:\n                # boolean numpy mask\n                self._s = self.scatter(np.argwhere(key)[:, 0], value)._s\n            else:\n                s = self._from_pyseries(\n                    PySeries.new_u32(\"\", np.array(key, np.uint32), _strict=True)\n                )\n                self.__setitem__(s, value)\n        elif isinstance(key, (list, tuple)):\n            s = self._from_pyseries(sequence_to_pyseries(\"\", key, dtype=UInt32))\n            self.__setitem__(s, value)\n        else:\n            msg = f'cannot use \"{key!r}\" for indexing'\n            raise TypeError(msg)\n\n    def __array__(\n        self,\n        dtype: np.dtype[Any] | None = None,\n        copy: bool | None = None,  # noqa: FBT001\n    ) -> np.ndarray[Any, Any]:\n        \"\"\"\n        Return a NumPy ndarray with the given data type.\n\n        This method ensures a Polars Series can be treated as a NumPy ndarray.\n        It enables `np.asarray` and NumPy universal functions.\n\n        See the NumPy documentation for more information:\n        https://numpy.org/doc/stable/user/basics.interoperability.html#the-array-method\n\n        See Also\n        --------\n        __array_ufunc__","sourceCodeStart":1554,"sourceCodeEnd":1590,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/series/series.py#L1554-L1590","documentation":"The fallback raise in Series.__setitem__: the key is not an int, not a Series, not a numpy ndarray, and not a list/tuple, so Polars cannot interpret it as an index and prints the offending key via repr(). Notably, slices are NOT handled by this setter, so `s[0:2] = v` lands here too.","triggerScenarios":"`s[0:2] = 5` (slice key), `s['colname'] = 1` (string key), `s[{'a': 1}] = 1` (dict key), `s[1.5] = 0` (float key - only plain int is special-cased at the top).","commonSituations":"Pandas slice-assignment habits (`s.iloc[0:2] = 5`); trying label-based ('set by column name') assignment; float indices from computed positions; autocompleted generic code passing through the wrong key type.","solutions":["Replace slice keys with explicit positions: `s[[0, 1]] = v`, `s[np.arange(0, 2)] = v`, or `s[list(range(0, 2))] = v`.","Replace slice keys with a boolean mask: `s[[True, True] + [False] * (s.len() - 2)] = v`.","For label-based logic, remember Polars Series are positional - do assignment in a DataFrame with expressions instead.","Coerce float indices to int: `s[int(i)] = v`."],"exampleFix":"// before\ns = pl.Series([1, 2, 3])\ns[0:2] = 0  # TypeError: cannot use \"slice(0, 2, None)\" for indexing\n\n// after\ns[[0, 1]] = 0\n# or a mask:\ns[np.arange(s.len()) < 2] = 0","handlingStrategy":"validation","validationCode":"def normalize_key(s: pl.Series, key):\n    if isinstance(key, slice):\n        key = list(range(*key.indices(s.len())))\n    if isinstance(key, float):\n        key = int(key)\n    assert isinstance(key, (int, list, tuple, pl.Series)) or _is_np(key), f'bad key {key!r}'\n    return key","typeGuard":"def is_supported_setitem_key(key) -> bool:\n    return isinstance(key, (int, list, tuple)) or type(key).__module__.startswith('numpy') or isinstance(key, pl.Series)","tryCatchPattern":"try:\n    s[key] = value\nexcept TypeError as e:\n    if 'for indexing' not in str(e):\n        raise\n    s[list(range(key.start or 0, key.stop or s.len(), key.step or 1))] = value","preventionTips":["Slices are not keys - expand them to positions or a boolean mask first.","Never use string labels or dicts as Series keys; Polars is positional.","Wrap Series access in a small helper that whitelists key types."],"tags":["polars","series","setitem","indexing","slice","key-type"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}