{"record":{"id":"e754e02723bb95fb","repo":"pandas-dev/pandas","slug":"cannot-add-indices-of-unequal-length","errorCode":null,"errorMessage":"cannot add indices of unequal length","messagePattern":"cannot add indices of unequal length","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/datetimelike.py","lineNumber":1112,"sourceCode":"        self = cast(\"DatetimeArray\", self)\n        # subtract a datetime from myself, yielding an ndarray[timedelta64[ns]]\n\n        if isna(other):\n            # i.e. np.datetime64(\"NaT\")\n            return self - NaT\n\n        ts = Timestamp(other)\n\n        self, ts = self._ensure_matching_resos(ts)\n        return self._sub_datetimelike(ts)\n\n    @final\n    def _sub_datetime_arraylike(self, other: DatetimeArray) -> TimedeltaArray:\n        if self.dtype.kind != \"M\":\n            raise TypeError(f\"cannot subtract a datelike from a {type(self).__name__}\")\n\n        if len(self) != len(other):\n            raise ValueError(\"cannot add indices of unequal length\")\n\n        self = cast(\"DatetimeArray\", self)\n\n        self, other = self._ensure_matching_resos(other)\n        return self._sub_datetimelike(other)\n\n    @final\n    def _sub_datetimelike(self, other: Timestamp | DatetimeArray) -> TimedeltaArray:\n        self = cast(\"DatetimeArray\", self)\n\n        from pandas.core.arrays import TimedeltaArray\n\n        try:\n            self._assert_tzawareness_compat(other)\n        except TypeError as err:\n            new_message = str(err).replace(\"compare\", \"subtract\")\n            raise type(err)(new_message) from err\n","sourceCodeStart":1094,"sourceCodeEnd":1130,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/datetimelike.py#L1094-L1130","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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."],"exampleFix":"// before\nres = dta_a - dta_b  # ValueError if len(dta_a) != len(dta_b)\n\n// after\ncommon = dta_a.get_indexer(dta_b)  # or reindex as appropriate\nres = dta_a - dta_a.reindex_like(dta_b)","handlingStrategy":"validation","validationCode":"import pandas as pd\n\ndef sub_aligned(a, b):\n    if len(a) != len(b):\n        a = pd.Series(a)\n        b = pd.Series(b).reindex(a.index) if hasattr(b, 'index') else pd.Series(b, index=a.index)\n    return a - b","typeGuard":null,"tryCatchPattern":"try:\n    res = a - b\nexcept ValueError as e:\n    if 'unequal length' in str(e):\n        res = pd.Series(a) - pd.Series(b)  # rely on index alignment\n    else:\n        raise","preventionTips":["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."],"tags":["datetime","arithmetic","shape-mismatch","value-error"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}