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 (and reused textually for sibling ops) when len(self) != len(other). DatetimeArray elementwise subtraction requires equal-length arrays; pandas does not broadcast datetimelike arrays against each other in this path.
Solutions
- Reindex or align the two arrays to equal length first (e.g. .reindex_like, Index alignment, or pd.Series arithmetic with proper index).
- Filter both operands with the same mask so lengths match.
- If broadcasting a scalar is intended, pass a Timestamp rather than a length-1 DatetimeArray.
Example fix
// before res = dta_a - dta_b # ValueError if len(dta_a) != len(dta_b) // after common = dta_a.get_indexer(dta_b) # or reindex as appropriate res = dta_a - dta_a.reindex_like(dta_b)
Defensive patterns
Strategy: validation
Validate before calling
import pandas as pd
def sub_aligned(a, b):
if len(a) != len(b):
a = pd.Series(a)
b = pd.Series(b).reindex(a.index) if hasattr(b, 'index') else pd.Series(b, index=a.index)
return a - b Try / catch
try:
res = a - b
except ValueError as e:
if 'unequal length' in str(e):
res = pd.Series(a) - pd.Series(b) # rely on index alignment
else:
raise Prevention
- Use pd.Series arithmetic to get automatic index alignment instead of raw array subtraction.
- Reindex both operands with .reindex_like before subtracting Index objects.
- Filter both operands with the same boolean mask to preserve length parity.
When it happens
Trigger: DatetimeArray.__sub__ where the two arrays have different lengths; df[date_col_a] - df[date_col_b] with misaligned indexes that did not get reindexed; subtracting DatetimeIndex objects of different lengths.
Common situations: Misaligned DataFrame indexes after a filter/groupby that are not reindexed; concatenating arrays from different sources without length checks; subtracting a slice against the full array.
Related errors
- abs(axis) must be less than ndim
- cannot add Period to a
- Cannot add and
- cannot add and
- Cannot modify read-only array
AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11).
Data as JSON: /api/errors/e754e02723bb95fb.
Report an issue: GitHub.
Appendix: 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 3b7651241d)