pandas-dev/pandas · error · ValueError
cannot add indices of unequal length
Error message
cannot add indices of unequal length
What it means
Raised by _sub_datetime_arraylike when len(self) != len(other). DatetimeArray subtraction is elementwise (no broadcasting between two arrays), so unequal lengths are rejected with ValueError. Despite the word 'add' in the message, this guards a subtraction.
Source
Thrown at pandas/core/arrays/datetimelike.py:1112
self = cast("DatetimeArray", self)
# subtract a datetime from myself, yielding an ndarray[timedelta64[ns]]
if isna(other):
# i.e. np.datetime64("NaT")
return self - NaT
ts = Timestamp(other)
self, ts = self._ensure_matching_resos(ts)
return self._sub_datetimelike(ts)
@final
def _sub_datetime_arraylike(self, other: DatetimeArray) -> TimedeltaArray:
if self.dtype.kind != "M":
raise TypeError(f"cannot subtract a datelike from a {type(self).__name__}")
if len(self) != len(other):
raise ValueError("cannot add indices of unequal length")
self = cast("DatetimeArray", self)
self, other = self._ensure_matching_resos(other)
return self._sub_datetimelike(other)
@final
def _sub_datetimelike(self, other: Timestamp | DatetimeArray) -> TimedeltaArray:
self = cast("DatetimeArray", self)
from pandas.core.arrays import TimedeltaArray
try:
self._assert_tzawareness_compat(other)
except TypeError as err:
new_message = str(err).replace("compare", "subtract")
raise type(err)(new_message) from err
View on GitHub (pinned to 71959b8cb9)
Solutions
- Align both arrays to a common index first: idx_a, idx_b = idx_a.align(idx_b) (alignment broadcasts NaN/NaT as needed).
- Reindex one operand to the other's index: idx_b = idx_b.reindex(idx_a.index).
- Slice the longer operand so lengths match, or broadcast a scalar instead of an array.
- Confirm len(a) == len(b) with an assertion before the arithmetic.
Example fix
// before out = datetime_idx_a - datetime_idx_b # ValueError when lengths differ // after a, b = datetime_idx_a.align(datetime_idx_b) out = a - b
Defensive patterns
Strategy: validation
Validate before calling
if len(a) != len(b):
a, b = a.align(b)
assert len(a) == len(b)
out = a - b Try / catch
try:
out = a - b
except ValueError as e:
if 'unequal length' in str(e):
a, b = a.align(b)
out = a - b
else:
raise Prevention
- Align DatetimeIndex operands before subtraction.
- Assert equal lengths before elementwise datetime arithmetic.
- Use reindex to enforce a common index.
When it happens
Trigger: Subtracting two DatetimeIndex/DatetimeArray objects of different lengths: idx_a - idx_b where len(idx_a) != len(idx_b). Reached via __sub__ line 1412 then _sub_datetime_arraylike line 1111.
Common situations: Joining or aligning series whose indexes disagree; slicing one series but not the other before a datetime subtraction; misconfigured fixtures in tests.
Related errors
- left and right must have the same length
- Lengths must match to compare
- length mismatch: {len(self)} vs. {len(other)}
- operands have mismatched length {len(self)} and {len(other)}
- cannot broadcast result
AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07).
Data as JSON: /api/errors/e754e02723bb95fb.
Report an issue: GitHub.