pandas-dev/pandas · error · TypeError

cumprod not supported for Timedelta.

Error message

cumprod not supported for Timedelta.

What it means

Raised by TimedeltaArray._accumulate when name=='cumprod'. Cumulative product of timedeltas is not defined (multiplying two durations does not yield a duration), so pandas explicitly rejects it with a TypeError while allowing cumsum/cummin/cummax. This prevents meaningless operations from silently producing garbage.

Source

Thrown at pandas/core/arrays/timedeltas.py:427

            (), {"dtype": dtype, "out": out, "keepdims": keepdims}, fname="std"
        )

        result = nanops.nanstd(self._ndarray, axis=axis, skipna=skipna, ddof=ddof)
        if axis is None or self.ndim == 1:
            return self._box_func(result)
        return self._from_backing_data(result)

    # ----------------------------------------------------------------
    # Accumulations

    def _accumulate(self, name: str, *, skipna: bool = True, **kwargs):
        if name == "cumsum":
            op = getattr(datetimelike_accumulations, name)
            result = op(self._ndarray.copy(), skipna=skipna, **kwargs)

            return type(self)._simple_new(result, dtype=self.dtype)
        elif name == "cumprod":
            raise TypeError("cumprod not supported for Timedelta.")

        else:
            return super()._accumulate(name, skipna=skipna, **kwargs)

    # ----------------------------------------------------------------
    # Rendering Methods

    def _formatter(self, boxed: bool = False):
        from pandas.io.formats.format import get_format_timedelta64

        return get_format_timedelta64(self, box=True)

    def _format_native_types(
        self, *, na_rep: str | float = "NaT", date_format=None, **kwargs
    ) -> npt.NDArray[np.object_]:
        from pandas.io.formats.format import get_format_timedelta64

        # Relies on TimeDelta._repr_base

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Exclude timedelta columns before cumprod: `df.select_dtypes(exclude='timedelta').cumprod()`.
  2. If you meant cumulative sum of durations, use .cumsum() which is supported.
  3. If you need a product of magnitudes, operate on .dt.total_seconds() and re-wrap if meaningful.

Example fix

# before
s = pd.Series(pd.to_timedelta(['1s','2s','3s']))
s.cumprod()  # TypeError
# after
s.cumsum()  # cumulative duration sum
Defensive patterns

Strategy: validation

Validate before calling

import pandas as pd

def safe_cumprod(df):
    numeric = df.select_dtypes(exclude='timedelta')
    return numeric.cumprod()

Type guard

import pandas as pd
def is_not_timedelta(s) -> bool:
    return not pd.api.types.is_timedelta64_dtype(s)

Try / catch

try:
    return s.cumprod()
except TypeError as e:
    if 'cumprod not supported for Timedelta' in str(e):
        return s.cumsum()
    raise

Prevention

When it happens

Trigger: Calling `s.cumprod()`, `df.cumprod()`, or `.expanding().prod()` (via accumulation) on a timedelta64 Series/Index. The branch at timedeltas.py:427 raises for name=='cumprod'.

Common situations: Running generic .cumprod() over a whole DataFrame that includes duration columns; copy-paste from numeric pipelines; expecting time-arithmetic semantics that do not exist.

Related errors


AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07). Data as JSON: /api/errors/98723d3e3711ddbb. Report an issue: GitHub.