pandas-dev/pandas · error · TypeError
Cannot multiply '{self.dtype}' by bool, explicitly cast to i
Error message
Cannot multiply '{self.dtype}' by bool, explicitly cast to integers instead What it means
Raised by TimedeltaArray.__mul__ when the scalar operand is a Python/numpy bool (GH#58054). Multiplying a duration by True/False is almost always a bug (True repeats once, False yields zero-length/NaT), so pandas requires an explicit integer cast to make intent clear. The same restriction applies to bool-dtype arrays (line 545). This aligns with numpy's deprecation of bool*number arithmetic.
Source
Thrown at pandas/core/arrays/timedeltas.py:502
i8_result[nat_out] = iNaT
result = i8_result.view(self._ndarray.dtype)
return type(self)._simple_new(result, dtype=result.dtype)
def _mul_int_overflowsafe(self, i8_other: npt.NDArray[np.int64]) -> Self:
# GH#43178: mul_overflowsafe raises the low-level OverflowError; surface
# it as OutOfBoundsTimedelta to match pandas' other td64 overflow paths.
try:
i8_result = mul_overflowsafe(self.asi8, i8_other)
except OverflowError as err:
raise OutOfBoundsTimedelta("Overflow in int64 multiplication") from err
result = i8_result.view(self._ndarray.dtype)
return type(self)._simple_new(result, dtype=result.dtype)
@unpack_zerodim_and_defer("__mul__")
def __mul__(self, other) -> Self:
if is_scalar(other):
if lib.is_bool(other):
raise TypeError(
f"Cannot multiply '{self.dtype}' by bool, explicitly cast to "
"integers instead"
)
if lib.is_integer(other):
# GH#43178: detect int64 overflow rather than silently wrapping
# in the i8 cast below (e.g. a multiplier outside int64 bounds).
# TODO(numpy>=2.5): numpy detects this natively (numpy GH-31378)
# but raises OverflowError; once the numpy floor is >= 2.5, drop
# mul_overflowsafe and re-wrap numpy's error as
# OutOfBoundsTimedelta. The float path isn't covered and stays.
other = int(other)
if other > lib.i8max or other < -lib.i8max - 1:
raise OutOfBoundsTimedelta("Overflow in int64 multiplication")
i8_vals = self.asi8
if other != 0 and i8_vals.size:
# The extreme elements bound all products, so checking them
# with exact Python-int arithmetic lets the common
# no-overflow case use a vectorized multiply. NaTView on GitHub (pinned to 71959b8cb9)
Solutions
- Cast the bool to int: `td_arr * mask.astype('int64')` or `td_arr * int(mask)`.
- If you meant filtering, use boolean indexing `td_arr[mask]` instead of multiplication.
- Replace bool-as-multiplier logic with np.where if you need conditional scaling.
Example fix
# before
td_arr * (td_arr > pd.Timedelta(0)) # TypeError
# after
td_arr * (td_arr > pd.Timedelta(0)).astype('int64') Defensive patterns
Strategy: type-guard
Validate before calling
from pandas._libs import lib
def safe_td_mul(td_arr, other):
if lib.is_bool(other) or (hasattr(other, 'dtype') and other.dtype.kind == 'b'):
other = other.astype('int64') if hasattr(other, 'astype') else int(other)
return td_arr * other Type guard
from pandas._libs import lib
def is_bool_operand(other) -> bool:
if lib.is_bool(other):
return True
dt = getattr(other, 'dtype', None)
return dt is not None and dt.kind == 'b' Try / catch
try:
return td_arr * mask
except TypeError as e:
if 'Cannot multiply' in str(e) and 'bool' in str(e):
return td_arr * mask.astype('int64')
raise Prevention
- Never multiply durations by bool masks; use indexing or np.where.
- Cast bool operands to int explicitly.
- Lint for `timedelta *` near boolean expressions.
When it happens
Trigger: Executing `td_arr * True`, `td_arr * np.bool_(False)`, or `td_arr * bool_series`. The scalar check at timedeltas.py:501 uses lib.is_bool(other); the array check at line 543 uses other.dtype.kind=='b'.
Common situations: Using a boolean mask as a multiplier instead of as a selector; piping comparison results into arithmetic; legacy code relying on implicit bool-to-int coercion.
Related errors
- Cannot multiply StringArray by bools. Explicitly cast to int
- cannot add the type {type(other).__name__} to a {type(self).
- Cannot multiply with {type(other).__name__}
- operator '{op_name}' not implemented for bool dtypes
- Cannot add or subtract timedelta64[ns] dtype from {self.dtyp
AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07).
Data as JSON: /api/errors/e75367a212290305.
Report an issue: GitHub.