pandas-dev/pandas · error · TypeError

mean is not implemented for

Error message

mean is not implemented for {type(self).__name__} since the meaning is ambiguous.  An alternative is obj.to_timestamp(how='start').mean()

What it means

Raised by DatetimeLikeArrayMixin.mean when self.dtype is a PeriodDtype. Averaging Periods is ambiguous (Periods are ordinal within a freq, but the 'mean period' has no canonical interpretation across freq boundaries), so pandas refuses and points users at to_timestamp(how='start').mean() per GH#24757.

Solutions

  1. Convert to timestamps first: idx.to_timestamp(how='start').mean(), then optionally back with .to_period(freq).
  2. If you want the middle period, compute .astype('i8') or .astype('int64').mean() and round, then wrap in a Period (advanced; respects freq).
  3. Exclude Period columns from generic .mean() aggregations.

Example fix

// before
pidx.mean()  # TypeError

// after
pidx.to_timestamp(how='start').mean()  # Timestamp
# or, to return a Period:
import numpy as np
mid = int(np.floor(pidx.astype('int64').mean()))
pd.PeriodOrdinal(mid, freq=pidx.freq) if hasattr(pd, 'PeriodOrdinal') else pd.Period(mid, freq=pidx.freq)
Defensive patterns

Strategy: fallback

Validate before calling

import pandas as pd

def mean_safe(idx):
    if isinstance(getattr(idx, 'dtype', None), pd.PeriodDtype):
        return idx.to_timestamp(how='start').mean()
    return idx.mean()

Type guard

import pandas as pd

def is_period_index(a) -> bool:
    return isinstance(getattr(a, 'dtype', None), pd.PeriodDtype)

Try / catch

try:
    return idx.mean()
except TypeError as e:
    if 'mean is not implemented' in str(e):
        return idx.to_timestamp(how='start').mean()
    raise

Prevention

When it happens

Trigger: PeriodIndex.mean(); PeriodArray.mean(); df.groupby(...).mean() on a Period column; resample/downsample aggregations that route to mean.

Common situations: Reporting/dashboard code that calls .mean() generically across mixed-type columns; aggregating Period-indexed financial data without converting to timestamps.

Related errors


AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11). Data as JSON: /api/errors/2c5b75dcf563e190. Report an issue: GitHub.

Appendix: source

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

        >>> idx = pd.date_range("2001-01-01 00:00", periods=3)
        >>> idx
        DatetimeIndex(['2001-01-01', '2001-01-02', '2001-01-03'],
                      dtype='datetime64[us]', freq='D')
        >>> idx.mean()
        Timestamp('2001-01-02 00:00:00')

        For :class:`pandas.TimedeltaIndex`:

        >>> tdelta_idx = pd.to_timedelta([1, 2, 3], unit="D")
        >>> tdelta_idx
        TimedeltaIndex(['1 days', '2 days', '3 days'],
                        dtype='timedelta64[s]', freq=None)
        >>> tdelta_idx.mean()
        Timedelta('2 days 00:00:00')
        """
        if isinstance(self.dtype, PeriodDtype):
            # See discussion in GH#24757
            raise TypeError(
                f"mean is not implemented for {type(self).__name__} since the "
                "meaning is ambiguous.  An alternative is "
                "obj.to_timestamp(how='start').mean()"
            )

        result = nanops.nanmean(
            self._ndarray, axis=axis, skipna=skipna, mask=self.isna()
        )
        return self._wrap_reduction_result(axis, result)

    @_period_dispatch
    def median(self, *, axis: AxisInt | None = None, skipna: bool = True, **kwargs):
        nv.validate_median((), kwargs)

        if axis is not None and abs(axis) >= self.ndim:
            raise ValueError("abs(axis) must be less than ndim")

        result = nanops.nanmedian(self._ndarray, axis=axis, skipna=skipna)

View on GitHub (pinned to 3b7651241d)