pandas-dev/pandas · error · ValueError
Lengths must match to compare
Error message
Lengths must match to compare
What it means
Raised by BaseMaskedArray._comparison_method when 'other' is a 1-D list-like whose length differs from len(self). Element-wise comparison between masked arrays and 1-D structures requires equal length; pandas does not rebroadcast or pad.
Solutions
- Reindex or align both sides to a shared index before comparing.
- Trim or extend the operand so lengths match (e.g. other[:len(arr)]).
- Compare against a scalar or use isin() for membership tests instead of ==.
Example fix
// before arr == other[len(arr) - 1:] # wrong length // after aligned = other[:len(arr)] arr == aligned
Defensive patterns
Strategy: validation
Validate before calling
import numpy as np
other_arr = np.asarray(other)
if other_arr.ndim == 1 and len(other_arr) != len(arr):
raise ValueError(f'Length mismatch: {len(arr)} vs {len(other_arr)}')
result = arr == other_arr Type guard
def lengths_match(arr, other) -> bool:
import numpy as np
if np.isscalar(other):
return True
return len(other) == len(arr) Try / catch
try:
result = arr == other
except ValueError as e:
if 'Lengths must match' in str(e):
other = other[:len(arr)]
result = arr == other
else:
raise Prevention
- Align indexes (reindex) before comparing columns of different lengths.
- Slice or pad operands to len(arr) explicitly when intent is clear.
- Use isin for membership rather than == against arbitrary-length lists.
When it happens
Trigger: Comparing two masked arrays/Series of different lengths: arr1 == arr2 where len(arr1) != len(arr2); passing a list whose length differs from the array.
Common situations: Comparing columns from misaligned DataFrames without reindexing; comparing against a list literal of the wrong length; off-by-one after slicing or filtering.
Related errors
- can only perform ops with 1-d structures
- cannot broadcast result
- Cannot cast NaN value to Integer dtype.
- cannot convert float NaN to bool
- cannot convert NA to integer
AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11).
Data as JSON: /api/errors/5ac60f395a2d2cfe.
Report an issue: GitHub.
Appendix: source
Thrown at pandas/core/arrays/masked.py:1095
other, mask = other._data, other._mask
elif is_list_like(other):
if not isinstance(
other, (list, np.ndarray, ExtensionArray)
) and not ops.has_castable_attr(other):
warnings.warn(
f"Operation with {type(other).__name__} is deprecated. "
"In a future version these will be treated as scalar-like. "
"To retain the old behavior, explicitly wrap in a Series "
"instead.",
Pandas4Warning,
stacklevel=find_stack_level(),
)
other = np.asarray(other)
if other.ndim > 1:
raise NotImplementedError("can only perform ops with 1-d structures")
if len(self) != len(other):
raise ValueError("Lengths must match to compare")
if other is libmissing.NA:
# numpy does not handle pd.NA well as "other" scalar (it returns
# a scalar False instead of an array)
# This may be fixed by NA.__array_ufunc__. Revisit this check
# once that's implemented.
result = np.zeros(self._data.shape, dtype="bool")
mask = np.ones(self._data.shape, dtype="bool")
else:
with warnings.catch_warnings():
# numpy may show a FutureWarning or DeprecationWarning:
# elementwise comparison failed; returning scalar instead,
# but in the future will perform elementwise comparison
# before returning NotImplemented. We fall back to the correct
# behavior today, so that should be fine to ignore.
warnings.filterwarnings("ignore", "elementwise", FutureWarning)
warnings.filterwarnings("ignore", "elementwise", DeprecationWarning)
method = getattr(self._data, f"__{op.__name__}__")View on GitHub (pinned to 3b7651241d)