pola-rs/polars · error
expected values when selecting columns by boolean mask, got
Error message
expected {df.width} values when selecting columns by boolean mask, got {len(key)} What it means
Raised by Polars when selecting columns with a boolean mask whose length does not equal the DataFrame's width (number of columns). The mask must provide one True/False value per column so each column can be kept or dropped.
Solutions
- Build the mask with one value per column: len(mask) == df.width (use df.columns to drive it)
- If you actually want to filter ROWS, use df.filter(mask_series) or df[mask_series] on a Series context appropriate for rows
- Recompute the mask from the current DataFrame, e.g. mask = [c.startswith("x_") for c in df.columns]
Example fix
// before
mask = df["a"] > 0 # length == height (rows)
df[mask] # ValueError: expected df.width values...
// after
df.filter(df["a"] > 0) # row filtering
df[[c.startswith("x_") for c in df.columns]] # column filtering Defensive patterns
Strategy: validation
Validate before calling
mask = [c.startswith("x_") for c in df.columns]
assert len(mask) == df.width, f"mask len {len(mask)} != width {df.width}"
df2 = df[mask] Type guard
def is_column_mask(mask, df) -> bool:
return len(mask) == df.width and all(isinstance(v, (bool, bool)) or v is not None for v in mask) Try / catch
try:
out = df[mask]
except ValueError as e:
if "boolean mask" in str(e):
out = df.filter(mask) # probably a row mask
else:
raise Prevention
- Always build column masks from df.columns so lengths stay in sync
- Rebuild masks after any operation that changes DataFrame shape
- Use df.filter for row masks; reserve df[mask] for column masks
When it happens
Trigger: df[[True, False]] on a 3-column DataFrame; passing a row mask (length == df.height) to column selection, e.g. df[bool_array_over_rows] without transposing intent; np.where returning a 1-D array of different length than df.width.
Common situations: Confusing row masks with column masks (using df.height-sized mask in df[mask] which selects columns); filtering columns of a modified DataFrame with a mask built against an older, differently-shaped DataFrame.
Related errors
- Cannot apply operation on arrays of different lengths
- cannot create DataFrame from array with more than two…
- cannot initialize Series from DataFrame without any columns
- cannot select columns using key of type
- cannot select columns using NumPy array of type
AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18).
Data as JSON: /api/errors/ab30d01b9ae3cc4c.
Report an issue: GitHub.
Appendix: 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 fe841f959e)