pandas-dev/pandas · error · ValueError
Cannot multiply with unequal lengths
Error message
Cannot multiply with unequal lengths
What it means
Raised in TimedeltaArray.__mul__ when the array operand's length differs from the timedelta array's length, except when the operand is itself timedelta64 (which is dispatched to a type-error path instead). This is the standard broadcast-length guard for elementwise multiplication.
Solutions
- Ensure both operands have equal length.
- Use pandas Series/Index objects so index alignment applies automatically, then drop or fill NaNs as needed.
- Broadcast a scalar instead of a length-mismatched array if a uniform scale was intended.
Example fix
# before pd.to_timedelta([1, 2, 3], unit='D') * np.array([1, 2]) # ValueError # after pd.to_timedelta([1, 2, 3], unit='D') * np.array([1, 2, 3])
Defensive patterns
Strategy: validation
Validate before calling
def lengths_match(a, b) -> bool:
return len(a) == len(b) Type guard
null
Try / catch
try:
result = td * other
except ValueError as e:
if 'unequal lengths' in str(e):
# align via Series or trim to common length
raise
raise Prevention
- Use pandas Series for automatic index alignment, or assert equal lengths up front.
- Broadcast scalars when uniform scaling is intended.
When it happens
Trigger: `pd.to_timedelta([1, 2, 3], unit='D') * np.array([1, 2])`, or multiplying two Series of different lengths without alignment.
Common situations: Forgetting that raw numpy arrays/lists do not align by index; mismatched filter or weight arrays.
Related errors
- Cannot divide vectors with unequal lengths
- cannot broadcast result
- Cannot multiply ' ' by bool, explicitly cast to integers…
- Cannot multiply with
- dtype ' ' is invalid, should be np.timedelta64 dtype
AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11).
Data as JSON: /api/errors/7cc3da00a1d96f78.
Report an issue: GitHub.
Appendix: source
Thrown at pandas/core/arrays/timedeltas.py:575
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 3b7651241d)