{"record":{"id":"7cc3da00a1d96f78","repo":"pandas-dev/pandas","slug":"cannot-multiply-with-unequal-lengths","errorCode":null,"errorMessage":"Cannot multiply with unequal lengths","messagePattern":"Cannot multiply with unequal lengths","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/timedeltas.py","lineNumber":556,"sourceCode":"\n        if not hasattr(other, \"dtype\"):\n            # list, tuple\n            other = np.array(other)\n\n        if other.dtype.kind == \"b\":\n            # GH#58054\n            raise TypeError(\n                f\"Cannot multiply '{self.dtype}' by bool, explicitly cast to \"\n                \"integers instead\"\n            )\n        if isinstance(other.dtype, (ArrowDtype, BaseMaskedDtype)):\n            # GH#58054\n            return NotImplemented\n\n        if len(other) != len(self) and not lib.is_np_dtype(other.dtype, \"m\"):\n            # Exclude timedelta64 here so we correctly raise TypeError\n            #  for that instead of ValueError\n            raise ValueError(\"Cannot multiply with unequal lengths\")\n\n        if is_object_dtype(other.dtype):\n            # this multiplication will succeed only if all elements of other\n            #  are int or float scalars, so we will end up with\n            #  timedelta64[ns]-dtyped result\n            arr = self._ndarray\n            obj_result = np.array([arr[n] * other[n] for n in range(len(self))])\n            return type(self)._simple_new(obj_result, dtype=obj_result.dtype)\n\n        if other.dtype.kind in \"iu\":\n            # GH#43178: detect int64 overflow rather than silently wrapping.\n            #  Cast to int64 first: an unsigned multiplier above int64.max wraps\n            #  to negative, which we detect by sign. We check the sign rather\n            #  than ``other > i8max`` because comparing a broadcast unsigned\n            #  array to a Python int segfaults on numpy < 2.2 (hit via the\n            #  DataFrame blockwise path).\n            i8_other = other.astype(\"i8\", copy=False)\n            if other.dtype.kind == \"u\" and (i8_other < 0).any():","sourceCodeStart":538,"sourceCodeEnd":574,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/timedeltas.py#L538-L574","documentation":"Raised by TimedeltaArray.__mul__ when multiplying against an array operand whose length differs from self, and whose dtype is not timedelta64 (timedelta is excluded so it can surface a TypeError elsewhere). Pandas requires length-matched operands for vectorized scaling to avoid silent broadcasting mistakes.","triggerScenarios":"`pd.to_timedelta(['1d','2d','3d']) * np.array([1,2])` or `td_series * int_series_of_different_len`. Hit in the array branch after list/tuple conversion to np.ndarray.","commonSituations":"Misaligned indices/Series from merges or filters; reusing a multiplier computed on a filtered subset; off-by-one in user-constructed arrays.","solutions":["Reindex or align both operands to the same length/index before multiplying.","Filter the longer operand to match, or broadcast a scalar instead of an array.","If lengths differ by design, decide the intended semantics (pairwise vs broadcast) and reindex explicitly."],"exampleFix":"// before\nout = td_series * mult_series  # different lengths\n\n// after\nmult = mult_series.reindex(td_series.index, fill_value=1)\nout = td_series * mult","handlingStrategy":"validation","validationCode":"import numpy as np\na, b = np.asarray(td), np.asarray(other)\nassert a.shape[0] == b.shape[0], f'length mismatch: {a.shape[0]} vs {b.shape[0]}'","typeGuard":"def lengths_match(a, b) -> bool:\n    return len(a) == len(b)","tryCatchPattern":"try:\n    out = td * other\nexcept ValueError as e:\n    if 'unequal lengths' in str(e):\n        other = other.reindex(td.index) if hasattr(other, 'reindex') else other[:len(td)]\n        out = td * other\n    else:\n        raise","preventionTips":["Align indices via reindex before multiplying.","Validate array lengths at function boundaries.","Prefer scalar multipliers when uniform scaling is intended."],"tags":["timedelta","valueerror","shape-mismatch","arithmetic"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}