pola-rs/polars · error · TypeError

selecting rows by passing a boolean mask to `__getitem__` is

Error message

selecting rows by passing a boolean mask to `__getitem__` is not supported\n\nHint: Use the `filter` method instead.

What it means

polars deliberately does not support boolean row masks in __getitem__: a bool Sequence, bool pl.Series, or bool numpy array used as a row key routes to _raise_on_boolean_mask (getitem.py:457), which points to filter. Column masks in the second slot (df[:, bool_mask]) are supported (see error 41); this error is only about the row slot.

Source

Thrown at py-polars/src/polars/_utils/getitem.py:457

        else:
            if arr.dtype in (np.int8, np.int16, np.int32):
                arr = arr.astype(np.int64)

        # Update negative indexes to absolute indexes.
        arr = np.where(arr < 0, size + arr, arr)

    # numpy conversion is much faster
    arr = arr.astype(np.uint32) if idx_type == UInt32 else arr.astype(np.uint64)

    return pl.Series("", arr, dtype=idx_type)


def _raise_on_boolean_mask() -> NoReturn:
    msg = (
        "selecting rows by passing a boolean mask to `__getitem__` is not supported"
        "\n\nHint: Use the `filter` method instead."
    )
    raise TypeError(msg)

View on GitHub (pinned to df599052da)

Solutions

  1. Use DataFrame.filter: df.filter(pl.col('x') > 0) or df.filter(bool_series)
  2. For Series: s.filter(s > 0)
  3. If positions are truly needed: idx = np.flatnonzero(mask.to_numpy()); df[idx]

Example fix

# before
df[df["x"] > 0]

# after
df.filter(pl.col("x") > 0)
Defensive patterns

Strategy: fallback

Validate before calling

def select_rows(frame, key):
    if isinstance(key, pl.Series) and key.dtype == pl.Boolean:
        return frame.filter(key)          # supported path
    if isinstance(key, list) and key and isinstance(key[0], bool):
        return frame.filter(pl.Series(key))
    return frame[key]

Type guard

import polars as pl

def is_boolean_mask(key) -> bool:
    if isinstance(key, pl.Series):
        return key.dtype == pl.Boolean
    if isinstance(key, (list, tuple)):
        return bool(key) and isinstance(key[0], bool)
    return False

Try / catch

try:
    out = df[mask]
except TypeError as exc:
    if "boolean mask" in str(exc):
        out = df.filter(mask)
    else:
        raise

Prevention

When it happens

Trigger: df[df['x'] > 0]; df[[True, False, True]]; df[np.array([True, False])]; df[bool_series] returned by an expression; s[bool_mask] on a Series.

Common situations: Muscle memory from pandas/NumPy boolean indexing; ported notebooks; condition Series produced by pl.col comparisons then passed to [].

Related errors


AI-assisted analysis of pola-rs/polars@df599052da (2026-08-16). Data as JSON: /api/errors/6041f2c2e3f7fb84. Report an issue: GitHub.