pola-rs/polars · error · ValueError

expected {df.width} values when selecting columns by boolean

Error message

expected {df.width} values when selecting columns by boolean mask, got {len(key)}

What it means

df[:, boolean_mask] selects columns by mask via _select_columns_by_mask (getitem.py:277). The mask must contain exactly one boolean per column (df.width); a mismatch raises this ValueError before anything is selected. In practice the mask is usually sized to df.height because it was computed from row data instead of the column list.

Source

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

    )
    raise TypeError(msg)


def _select_columns_by_index(df: DataFrame, key: Iterable[int]) -> DataFrame:
    series = [df.to_series(i) for i in key]
    return df.__class__(series)


def _select_columns_by_name(df: DataFrame, key: Iterable[str]) -> DataFrame:
    return df._from_pydf(df._df.select(list(key)))


def _select_columns_by_mask(
    df: DataFrame, key: Sequence[bool] | Series | np.ndarray[Any, Any]
) -> DataFrame:
    if len(key) != df.width:
        msg = f"expected {df.width} values when selecting columns by boolean mask, got {len(key)}"
        raise ValueError(msg)

    indices = (i for i, val in enumerate(key) if val)
    return _select_columns_by_index(df, indices)


@overload
def _select_rows(df: DataFrame, key: SingleIndexSelector) -> Series: ...


@overload
def _select_rows(df: DataFrame, key: MultiIndexSelector) -> DataFrame: ...


def _select_rows(
    df: DataFrame, key: SingleIndexSelector | MultiIndexSelector
) -> DataFrame | Series:
    """Select one or more rows from the DataFrame."""
    if isinstance(key, int):

View on GitHub (pinned to df599052da)

Solutions

  1. For row filtering use df.filter(pl.col('flag')) instead of putting the mask in the column slot
  2. Build a true column mask from df.columns: keep = [c.startswith('n_') for c in df.columns]; df[:, keep]
  3. Or select names directly: df.select([c for c, k in zip(df.columns, mask) if k])

Example fix

# before
df[:, df["flag"].to_list()]  # len == df.height, not df.width

# after
df.filter(pl.col("flag"))
Defensive patterns

Strategy: validation

Validate before calling

mask = [c.startswith("n_") for c in df.columns]  # build from columns, not rows
assert len(mask) == df.width, f"mask len {len(mask)} != width {df.width}"

Type guard

def is_column_mask_valid(df, mask) -> bool:
    return len(mask) == df.width and all(isinstance(v, (bool, np.bool_)) for v in mask)

Prevention

When it happens

Trigger: df[:, [True, False, True]] on a frame with 2 or 4 columns; df[:, bool_np_array] where len(array) == df.height; df[:, df['flag'].to_list()] (mask built from a row column); schema changed (columns added/removed) after the mask was computed.

Common situations: Row/column slot confusion in tuple indexing (row filter placed in the column slot); masks generated from an earlier schema version of the frame; copying df[df['flag'].values] pandas idiom into the second slot.

Related errors


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