pandas-dev/pandas · error · ValueError
Cannot multiply with unequal lengths
Error message
Cannot multiply with unequal lengths
What it means
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.
Source
Thrown at pandas/core/arrays/timedeltas.py:556
if not hasattr(other, "dtype"):
# list, tuple
other = np.array(other)
if other.dtype.kind == "b":
# GH#58054
raise TypeError(
f"Cannot multiply '{self.dtype}' by bool, explicitly cast to "
"integers instead"
)
if isinstance(other.dtype, (ArrowDtype, BaseMaskedDtype)):
# GH#58054
return NotImplemented
if len(other) != len(self) and not lib.is_np_dtype(other.dtype, "m"):
# Exclude timedelta64 here so we correctly raise TypeError
# for that instead of ValueError
raise ValueError("Cannot multiply with unequal lengths")
if is_object_dtype(other.dtype):
# this multiplication will succeed only if all elements of other
# are int or float scalars, so we will end up with
# timedelta64[ns]-dtyped result
arr = self._ndarray
obj_result = np.array([arr[n] * other[n] for n in range(len(self))])
return type(self)._simple_new(obj_result, dtype=obj_result.dtype)
if other.dtype.kind in "iu":
# GH#43178: detect int64 overflow rather than silently wrapping.
# Cast to int64 first: an unsigned multiplier above int64.max wraps
# to negative, which we detect by sign. We check the sign rather
# than ``other > i8max`` because comparing a broadcast unsigned
# array to a Python int segfaults on numpy < 2.2 (hit via the
# DataFrame blockwise path).
i8_other = other.astype("i8", copy=False)
if other.dtype.kind == "u" and (i8_other < 0).any():View on GitHub (pinned to 71959b8cb9)
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.
Example fix
// before out = td_series * mult_series # different lengths // after mult = mult_series.reindex(td_series.index, fill_value=1) out = td_series * mult
Defensive patterns
Strategy: validation
Validate before calling
import numpy as np
a, b = np.asarray(td), np.asarray(other)
assert a.shape[0] == b.shape[0], f'length mismatch: {a.shape[0]} vs {b.shape[0]}' Type guard
def lengths_match(a, b) -> bool:
return len(a) == len(b) Try / catch
try:
out = td * other
except ValueError as e:
if 'unequal lengths' in str(e):
other = other.reindex(td.index) if hasattr(other, 'reindex') else other[:len(td)]
out = td * other
else:
raise Prevention
- Align indices via reindex before multiplying.
- Validate array lengths at function boundaries.
- Prefer scalar multipliers when uniform scaling is intended.
When it happens
Trigger: `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.
Common situations: Misaligned indices/Series from merges or filters; reusing a multiplier computed on a filtered subset; off-by-one in user-constructed arrays.
Related errors
- Cannot divide vectors with unequal lengths
- Function did not transform
- Cannot add or subtract timedelta64[ns] dtype from {self.dtyp
- Cannot add/subtract timedelta-like from PeriodArray that is
- Values resolution does not match dtype.
AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07).
Data as JSON: /api/errors/7cc3da00a1d96f78.
Report an issue: GitHub.