pandas-dev/pandas · error · ValueError

left and right must have the same length

Error message

left and right must have the same length

What it means

Raised by `_validate` when `len(left) != len(right)`. Intervals are pairwise, so the two bound arrays must align element-by-element. Fires at pandas/core/arrays/interval.py:612.

Source

Thrown at pandas/core/arrays/interval.py:612

    @classmethod
    def _validate(cls, left, right, dtype: IntervalDtype) -> None:
        """
        Verify that the IntervalArray is valid.

        Checks that

        * dtype is correct
        * left and right match lengths
        * left and right have the same missing values
        * left is always below right
        """
        if not isinstance(dtype, IntervalDtype):
            msg = f"invalid dtype: {dtype}"
            raise ValueError(msg)
        if len(left) != len(right):
            msg = "left and right must have the same length"
            raise ValueError(msg)
        left_mask = notna(left)
        right_mask = notna(right)
        if not (left_mask == right_mask).all():
            msg = (
                "missing values must be missing in the same "
                "location both left and right sides"
            )
            raise ValueError(msg)
        if not (left[left_mask] <= right[left_mask]).all():
            msg = "left side of interval must be <= right side"
            raise ValueError(msg)

    def _shallow_copy(self, left, right) -> Self:
        """
        Return a new IntervalArray with the replacement attributes

        Parameters
        ----------

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Align both arrays to a common index before constructing: `left, right = left.align(right)`.
  2. Recompute breaks so `len(breaks) == n+1` if using `from_breaks`.
  3. Trim or pad explicitly after asserting the intended length matches.

Example fix

// before
pd.IntervalIndex.from_arrays(df['lo'].dropna(), df['hi'])
// after
lo, hi = df['lo'].align(df['hi'])
pd.IntervalIndex.from_arrays(lo, hi)
Defensive patterns

Strategy: validation

Validate before calling

def equal_length(left, right):
    if len(left) != len(right):
        raise ValueError(f"length mismatch: {len(left)} vs {len(right)}")
    return left, right

Type guard

def lengths_match(left, right) -> bool:
    return len(left) == len(right)

Try / catch

try:
    ia = pd.IntervalArray(left, right)
except ValueError as e:
    if "same length" in str(e):
        n = min(len(left), len(right))
        ia = pd.IntervalArray(left[:n], right[:n])
    else:
        raise

Prevention

When it happens

Trigger: `pd.IntervalIndex.from_arrays([0,1,2], [1,2])`, or after filtering/sorting one column independently of the other.

Common situations: Dropping NA from one side but not the other; groupby transforms that change length on only one column; off-by-one in break computation via `from_breaks`.

Related errors


AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07). Data as JSON: /api/errors/8c62c630fda41068. Report an issue: GitHub.