{"record":{"id":"eeb9c657b3290ee0","repo":"pandas-dev/pandas","slug":"lengths-must-match-eeb9c6","errorCode":null,"errorMessage":"Lengths must match","messagePattern":"Lengths must match","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/datetimelike.py","lineNumber":510,"sourceCode":"                # failed to parse as Timestamp/Timedelta/Period\n                raise InvalidComparison(other) from err\n\n        if isinstance(other, self._recognized_scalars) or other is NaT:\n            # error: Argument 1 to \"Timestamp\" has incompatible type \"object\";\n            # expected \"integer[Any] | float | str | date | datetime |\n            # datetime64[date | int | None]\"  [arg-type]\n            other = self._scalar_type(other)  # type: ignore[arg-type]\n            try:\n                self._check_compatible_with(other)\n            except TypeError as err:\n                # e.g. tzawareness mismatch\n                raise InvalidComparison(other) from err\n\n        elif not is_list_like(other):\n            raise InvalidComparison(other)\n\n        elif len(other) != len(self):\n            raise ValueError(\"Lengths must match\")\n\n        else:\n            try:\n                other = self._validate_listlike(other, allow_object=True)\n                self._check_compatible_with(other)\n            except TypeError as err:\n                if is_object_dtype(getattr(other, \"dtype\", None)):\n                    # We will have to operate element-wise\n                    pass\n                else:\n                    raise InvalidComparison(other) from err\n\n        return other\n\n    def _validate_scalar(\n        self,\n        value,\n        *,","sourceCodeStart":492,"sourceCodeEnd":528,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/datetimelike.py#L492-L528","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Verify lengths match: assert len(a) == len(b) before comparing.","Compare against a scalar (dti < Timestamp('2020-01-01')) for broadcasting.","Align via Series/Index operations so pandas handles index alignment instead of raw array comparison.","Use reindex or .reset_index(drop=True) to ensure parallel positioning before extracting .values."],"exampleFix":"# before\ndti1 < np.array([Timestamp('2020-01-01')])  # length mismatch if len(dti1) > 1\n\n# after\ndti1 < Timestamp('2020-01-01')  # scalar broadcast","handlingStrategy":"validation","validationCode":"other = np.asarray(other)\nif other.ndim == 0:\n    other = other.item()  # scalar broadcast path\nelif len(other) != len(arr):\n    raise ValueError(f'length {len(other)} != {len(arr)}')\narr < other","typeGuard":"def lengths_match(a, b) -> bool:\n    import numpy as np\n    a_len = 1 if np.ndim(a) == 0 else len(a)\n    b_len = 1 if np.ndim(b) == 0 else len(b)\n    return a_len == b_len or a_len == 1 or b_len == 1","tryCatchPattern":"try:\n    arr < other\nexcept ValueError as e:\n    if 'Lengths must match' in str(e):\n        arr < other[:len(arr)]\n    else:\n        raise","preventionTips":["Compare datetimelike arrays against scalars unless lengths are known equal.","Use pandas Series/Index ops to let alignment handle length differences."],"tags":["datetimelike","comparison","length-mismatch","broadcasting"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}