{"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":"TypeError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/series/series.py","lineNumber":1458,"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":1440,"sourceCodeEnd":1476,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/series/series.py#L1440-L1476","documentation":"Series.__setitem__ raises this TypeError when the key is not any supported index type (int, bool, Series, numpy array, or list/tuple of indices). The given key's repr is embedded in the message to show what was actually passed.","triggerScenarios":"`series[\"label\"] = value` (string key), `series[{'a': 1}] = value` (dict key), or any other non-sequence, non-int object at py-polars/src/polars/series/series.py:1458.","commonSituations":"Pandas habits of label-based indexing (`s['col'] = ...`) applied to a polars Series; passing a dict or slice-like object; confusing Series with DataFrame column selection.","solutions":["Use an integer position: `series[0] = value`","Use a boolean mask or integer Series: `series[s > 0] = value`","For label-like access, build a boolean mask or use DataFrame/Expr APIs (`with_columns`, `when/then`) instead of `__setitem__` with a string"],"exampleFix":"// before\ns[\"a\"] = 1  # TypeError\n// after\ns[0] = 1","handlingStrategy":"validation","validationCode":"valid = isinstance(key, (int, bool, pl.Series, list, tuple)) or (\n    isinstance(key, object) and type(key).__module__ == \"numpy\"\n)\nif not valid:\n    raise TypeError(\"Series keys must be int, bool, Series, ndarray, or list\")","typeGuard":"def is_settable_key(key: object) -> bool:\n    return isinstance(key, (int, bool, pl.Series, list, tuple, np.ndarray))","tryCatchPattern":"try:\n    series[key] = value\nexcept TypeError as e:\n    if 'for indexing' in str(e) or 'cannot use' in str(e):\n        series[np.flatnonzero(np.asarray(labels) == key)] = value  # label lookup\n    else:\n        raise","preventionTips":["Polars Series are positional — never index by string labels","Use DataFrame APIs for named-column logic","Wrap label lookups in explicit boolean masks"],"tags":["polars","python","setitem","invalid-key","type-error"],"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"}