{"record":{"id":"2c5b75dcf563e190","repo":"pandas-dev/pandas","slug":"mean-is-not-implemented-for-type-self-name","errorCode":null,"errorMessage":"mean is not implemented for {type(self).__name__} since the meaning is ambiguous.  An alternative is obj.to_timestamp(how='start').mean()","messagePattern":"mean is not implemented for (.+?) since the meaning is ambiguous\\.  An alternative is obj\\.to_timestamp\\(how='start'\\)\\.mean\\(\\)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/datetimelike.py","lineNumber":1585,"sourceCode":"        >>> idx = pd.date_range(\"2001-01-01 00:00\", periods=3)\n        >>> idx\n        DatetimeIndex(['2001-01-01', '2001-01-02', '2001-01-03'],\n                      dtype='datetime64[us]', freq='D')\n        >>> idx.mean()\n        Timestamp('2001-01-02 00:00:00')\n\n        For :class:`pandas.TimedeltaIndex`:\n\n        >>> tdelta_idx = pd.to_timedelta([1, 2, 3], unit=\"D\")\n        >>> tdelta_idx\n        TimedeltaIndex(['1 days', '2 days', '3 days'],\n                        dtype='timedelta64[s]', freq=None)\n        >>> tdelta_idx.mean()\n        Timedelta('2 days 00:00:00')\n        \"\"\"\n        if isinstance(self.dtype, PeriodDtype):\n            # See discussion in GH#24757\n            raise TypeError(\n                f\"mean is not implemented for {type(self).__name__} since the \"\n                \"meaning is ambiguous.  An alternative is \"\n                \"obj.to_timestamp(how='start').mean()\"\n            )\n\n        result = nanops.nanmean(\n            self._ndarray, axis=axis, skipna=skipna, mask=self.isna()\n        )\n        return self._wrap_reduction_result(axis, result)\n\n    @_period_dispatch\n    def median(self, *, axis: AxisInt | None = None, skipna: bool = True, **kwargs):\n        nv.validate_median((), kwargs)\n\n        if axis is not None and abs(axis) >= self.ndim:\n            raise ValueError(\"abs(axis) must be less than ndim\")\n\n        result = nanops.nanmedian(self._ndarray, axis=axis, skipna=skipna)","sourceCodeStart":1567,"sourceCodeEnd":1603,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/datetimelike.py#L1567-L1603","documentation":"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.","triggerScenarios":"PeriodIndex.mean(); PeriodArray.mean(); df.groupby(...).mean() on a Period column; resample/downsample aggregations that route to mean.","commonSituations":"Reporting/dashboard code that calls .mean() generically across mixed-type columns; aggregating Period-indexed financial data without converting to timestamps.","solutions":["Convert to timestamps first: idx.to_timestamp(how='start').mean(), then optionally back with .to_period(freq).","If you want the middle period, compute .astype('i8') or .astype('int64').mean() and round, then wrap in a Period (advanced; respects freq).","Exclude Period columns from generic .mean() aggregations."],"exampleFix":"// before\npidx.mean()  # TypeError\n\n// after\npidx.to_timestamp(how='start').mean()  # Timestamp\n# or, to return a Period:\nimport numpy as np\nmid = int(np.floor(pidx.astype('int64').mean()))\npd.PeriodOrdinal(mid, freq=pidx.freq) if hasattr(pd, 'PeriodOrdinal') else pd.Period(mid, freq=pidx.freq)","handlingStrategy":"fallback","validationCode":"import pandas as pd\n\ndef mean_safe(idx):\n    if isinstance(getattr(idx, 'dtype', None), pd.PeriodDtype):\n        return idx.to_timestamp(how='start').mean()\n    return idx.mean()","typeGuard":"import pandas as pd\n\ndef is_period_index(a) -> bool:\n    return isinstance(getattr(a, 'dtype', None), pd.PeriodDtype)","tryCatchPattern":"try:\n    return idx.mean()\nexcept TypeError as e:\n    if 'mean is not implemented' in str(e):\n        return idx.to_timestamp(how='start').mean()\n    raise","preventionTips":["Convert PeriodIndex to timestamps before calling .mean().","Exclude Period columns from generic .mean() pipelines.","For an integer midpoint, use .astype('int64').mean() and wrap back into a Period."],"tags":["datetime","reduction","period","mean","type-error"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}