pandas-dev/pandas · error · ValueError

Lengths must match

Error message

Lengths must match

What it means

Raised in DatetimeLikeArray._validate_comparison_value when the other operand is list-like but its length differs from the array. Comparison operators between datetimelike arrays require element-wise alignment, so length mismatch would broadcast incorrectly. Earlier branches handle scalars and non-list-likes; this branch specifically catches array-vs-array length mismatch before tz/unit compatibility is checked.

Solutions

  1. Verify lengths match: assert len(a) == len(b) before comparing.
  2. Compare against a scalar (dti < Timestamp('2020-01-01')) for broadcasting.
  3. Align via Series/Index operations so pandas handles index alignment instead of raw array comparison.
  4. Use reindex or .reset_index(drop=True) to ensure parallel positioning before extracting .values.

Example fix

# before
dti1 < np.array([Timestamp('2020-01-01')])  # length mismatch if len(dti1) > 1

# after
dti1 < Timestamp('2020-01-01')  # scalar broadcast
Defensive patterns

Strategy: validation

Validate before calling

other = np.asarray(other)
if other.ndim == 0:
    other = other.item()  # scalar broadcast path
elif len(other) != len(arr):
    raise ValueError(f'length {len(other)} != {len(arr)}')
arr < other

Type guard

def lengths_match(a, b) -> bool:
    import numpy as np
    a_len = 1 if np.ndim(a) == 0 else len(a)
    b_len = 1 if np.ndim(b) == 0 else len(b)
    return a_len == b_len or a_len == 1 or b_len == 1

Try / catch

try:
    arr < other
except ValueError as e:
    if 'Lengths must match' in str(e):
        arr < other[:len(arr)]
    else:
        raise

Prevention

When it happens

Trigger: dti1 < dti2 where len(dti1) != len(dti2). dti == np.array([...]) with a different length. Series comparison where index alignment was disabled or values were extracted. Comparing a DatetimeIndex to a list of timestamps of the wrong length.

Common situations: Off-by-one in slicing produces mismatched lengths. Comparing a column to a row from the same frame (different length). Concatenation errors leaving an extra element. Using .values to compare arrays of different shape after a groupby.

Related errors


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

Appendix: source

Thrown at pandas/core/arrays/datetimelike.py:510

                # failed to parse as Timestamp/Timedelta/Period
                raise InvalidComparison(other) from err

        if isinstance(other, self._recognized_scalars) or other is NaT:
            # error: Argument 1 to "Timestamp" has incompatible type "object";
            # expected "integer[Any] | float | str | date | datetime |
            # datetime64[date | int | None]"  [arg-type]
            other = self._scalar_type(other)  # type: ignore[arg-type]
            try:
                self._check_compatible_with(other)
            except TypeError as err:
                # e.g. tzawareness mismatch
                raise InvalidComparison(other) from err

        elif not is_list_like(other):
            raise InvalidComparison(other)

        elif len(other) != len(self):
            raise ValueError("Lengths must match")

        else:
            try:
                other = self._validate_listlike(other, allow_object=True)
                self._check_compatible_with(other)
            except TypeError as err:
                if is_object_dtype(getattr(other, "dtype", None)):
                    # We will have to operate element-wise
                    pass
                else:
                    raise InvalidComparison(other) from err

        return other

    def _validate_scalar(
        self,
        value,
        *,

View on GitHub (pinned to 3b7651241d)