pandas-dev/pandas · error · ValueError

Lengths must match

Error message

Lengths must match

What it means

Raised by BooleanArray._logical_method when 'other' is array-like (not scalar) and its length differs from self. BooleanArray logical ops are element-wise, so the operands must align in length; otherwise the result would be ill-defined. The check fires before the Kleene dispatch.

Solutions

  1. Align the operands via a common pandas Index before the operation (Series will reindex).
  2. Broadcast a scalar instead of a length-mismatched array when you meant element-wise-constant.
  3. Verify len(other) == len(self) before the operation and trim/extend as needed.

Example fix

// before
s = pd.Series(pd.array([True, False, None], dtype='boolean'))
out = s & pd.array([True, False], dtype='boolean')
// after
s = pd.Series(pd.array([True, False, None], dtype='boolean'))
other = pd.Series(pd.array([True, False, True], dtype='boolean'), index=s.index)
out = s & other
Defensive patterns

Strategy: validation

Validate before calling

if not lib.is_scalar(other) and len(self) != len(other):
    raise ValueError(f'length mismatch: {len(self)} vs {len(other)}')

Type guard

def lengths_aligned(self_arr, other) -> bool:
    from pandas._libs import lib
    return lib.is_scalar(other) or len(self_arr) == len(other)

Try / catch

try:
    result = boolean_array & other
except ValueError as e:
    if 'Lengths must match' in str(e):
        other = other.reindex(boolean_array.index)
        ...

Prevention

When it happens

Trigger: boolean_series & pd.array([True, False], dtype='boolean') of a different length; boolean_array | [True, False, True, True] against a 3-element BooleanArray; mixing a BooleanArray with a list-like operand of mismatched length in &, |, ^.

Common situations: Broadcasting mistakes; operands drawn from columns of different DataFrames without alignment; off-by-one after filtering one operand but not the other; using a Python list of the wrong length.

Related errors


AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11). Data as JSON: /api/errors/1723e88ea4649597. Report an issue: GitHub.

Appendix: source

Thrown at pandas/core/arrays/boolean.py:427

                    Pandas4Warning,
                    stacklevel=find_stack_level(),
                )

            other = np.asarray(other, dtype="bool")
            if other.ndim > 1:
                return NotImplemented
            other, mask = coerce_to_array(other, copy=False)
        elif isinstance(other, np.bool_):
            other = other.item()

        if other_is_scalar and other is not libmissing.NA and not lib.is_bool(other):
            raise TypeError(
                "'other' should be pandas.NA or a bool. "
                f"Got {type(other).__name__} instead."
            )

        if not other_is_scalar and len(self) != len(other):
            raise ValueError("Lengths must match")

        if op.__name__ in {"or_", "ror_"}:
            result, mask = ops.kleene_or(self._data, other, self._mask, mask)
        elif op.__name__ in {"and_", "rand_"}:
            result, mask = ops.kleene_and(self._data, other, self._mask, mask)
        else:
            # i.e. xor, rxor
            result, mask = ops.kleene_xor(self._data, other, self._mask, mask)

        # i.e. BooleanArray
        return self._maybe_mask_result(result, mask)

    def _accumulate(
        self, name: str, *, skipna: bool = True, **kwargs
    ) -> BaseMaskedArray:
        data = self._data
        mask = self._mask
        if name in ("cummin", "cummax"):

View on GitHub (pinned to 3b7651241d)