pandas-dev/pandas · error · TypeError

Period type does not support {how} operations

Error message

Period type does not support {how} operations

What it means

Raised by _groupby_op when grouping a PeriodDtype column with how in {sum/prod/cumsum/cumprod/var/skew/kurt}. As with datetime64 (error 256) these reductions are not meaningful on absolute Period values and are rejected.

Source

Thrown at pandas/core/arrays/datetimelike.py:1635

        ids: npt.NDArray[np.intp],
        **kwargs,
    ):
        dtype = self.dtype
        if dtype.kind == "M":
            # Adding/multiplying datetimes is not valid
            if how in ["sum", "prod", "cumsum", "cumprod", "var", "skew", "kurt"]:
                raise TypeError(f"datetime64 type does not support operation '{how}'")
            if how in ["any", "all"]:
                # GH#34479
                raise TypeError(
                    f"'{how}' with datetime64 dtypes is no longer supported. "
                    f"Use (obj != pd.Timestamp(0)).{how}() instead."
                )

        elif isinstance(dtype, PeriodDtype):
            # Adding/multiplying Periods is not valid
            if how in ["sum", "prod", "cumsum", "cumprod", "var", "skew", "kurt"]:
                raise TypeError(f"Period type does not support {how} operations")
            if how in ["any", "all"]:
                # GH#34479
                raise TypeError(
                    f"'{how}' with PeriodDtype is no longer supported. "
                    f"Use (obj != pd.Period(0, freq)).{how}() instead."
                )
        # timedeltas we can add but not multiply
        elif how in ["prod", "cumprod", "skew", "kurt", "var"]:
            raise TypeError(f"timedelta64 type does not support {how} operations")

        # All of the functions implemented here are ordinal, so we can
        #  operate on the tz-naive equivalents
        npvalues = self._ndarray.view("M8[ns]")

        from pandas.core.groupby.ops import WrappedCythonOp

        kind = WrappedCythonOp.get_kind_from_how(how)
        op = WrappedCythonOp(how=how, kind=kind, has_dropped_na=has_dropped_na)

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Convert the Period column to timestamp before reducing: df['p'].dt.to_timestamp(how='start').groupby(key).mean().
  2. Use supported reductions: .min/.max/.count/.median.
  3. Aggregate the ordinal: df['p'].view('i8').groupby(key).sum().
  4. Exclude Period columns from sum/prod-style aggregations.

Example fix

// before
df.groupby('key')['period_col'].sum()  # TypeError: Period type does not support sum operations
// after
df.groupby('key')['period_col'].agg(['min','max','count'])
Defensive patterns

Strategy: type-guard

Validate before calling

from pandas.api.types import is_period_dtype
BAD = {'sum','prod','cumsum','cumprod','var','skew','kurt'}
if is_period_dtype(col.dtype) and how in BAD:
    how = 'min'  # or skip the column

Type guard

def supports_groupby_op(col, how: str) -> bool:
    from pandas.api.types import is_period_dtype
    BAD = {'sum','prod','cumsum','cumprod','var','skew','kurt'}
    return not (is_period_dtype(col.dtype) and how in BAD)

Try / catch

try:
    out = df.groupby('key')['p'].agg(how)
except TypeError as e:
    if 'Period type does not support' in str(e):
        out = df.groupby('key')['p'].agg(['min','max','count'])
    else:
        raise

Prevention

When it happens

Trigger: df.groupby(key)[period_col].sum(), .prod(), .cumsum(), .var(), .skew(), .kurt(); reached via the branch at line 1632-1635.

Common situations: Generic aggregation pipelines run over Period columns; reporting code that summarises every column.

Related errors


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