pola-rs/polars · error · TypeError
cannot use " " for indexing
Error message
cannot use "{key!r}" for indexing What it means
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.
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
Example fix
// before s["a"] = 1 # TypeError // after s[0] = 1
Defensive patterns
Strategy: validation
Validate before calling
valid = isinstance(key, (int, bool, pl.Series, list, tuple)) or (
isinstance(key, object) and type(key).__module__ == "numpy"
)
if not valid:
raise TypeError("Series keys must be int, bool, Series, ndarray, or list") Type guard
def is_settable_key(key: object) -> bool:
return isinstance(key, (int, bool, pl.Series, list, tuple, np.ndarray)) Try / catch
try:
series[key] = value
except TypeError as e:
if 'for indexing' in str(e) or 'cannot use' in str(e):
series[np.flatnonzero(np.asarray(labels) == key)] = value # label lookup
else:
raise Prevention
- Polars Series are positional — never index by string labels
- Use DataFrame APIs for named-column logic
- Wrap label lookups in explicit boolean masks
When it happens
Trigger: `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.
Common situations: 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.
Understand the failure class
Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.
Related errors
- cannot set Series of dtype
- arr.to_struct() got a str instead of a list. hint: pass
- cannot call `map_groups` when filtering groups with `having`
- cannot call `map_groups` when grouping by an expression
- cannot call `map_groups` when grouping by named expressions
AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18).
Data as JSON: /api/errors/98fcf4a9181b04fa.
Report an issue: GitHub.
Appendix: source
Thrown at py-polars/src/polars/series/series.py:1458
msg = f"cannot use Series of dtype {key.dtype!r} for indexing; expected boolean or integer dtype"
raise TypeError(msg)
# TODO: implement for these types without casting to series
elif _check_for_numpy(key) and isinstance(key, np.ndarray):
if key.dtype == np.bool_:
# boolean numpy mask
self._s = self.scatter(np.argwhere(key)[:, 0], value)._s
else:
s = self._from_pyseries(
PySeries.new_u32("", np.array(key, np.uint32), _strict=True)
)
self.__setitem__(s, value)
elif isinstance(key, (list, tuple)):
s = self._from_pyseries(sequence_to_pyseries("", key, dtype=UInt32))
self.__setitem__(s, value)
else:
msg = f'cannot use "{key!r}" for indexing'
raise TypeError(msg)
def __array__(
self,
dtype: np.dtype[Any] | None = None,
copy: bool | None = None, # noqa: FBT001
) -> np.ndarray[Any, Any]:
"""
Return a NumPy ndarray with the given data type.
This method ensures a Polars Series can be treated as a NumPy ndarray.
It enables `np.asarray` and NumPy universal functions.
See the NumPy documentation for more information:
https://numpy.org/doc/stable/user/basics.interoperability.html#the-array-method
See Also
--------
__array_ufunc__View on GitHub (pinned to fe841f959e)