{"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":1576,"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":1558,"sourceCodeEnd":1594,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/datetimelike.py#L1558-L1594","documentation":"Raised by mean() when self.dtype is PeriodDtype (see GH#24757). Averaging absolute Period values is ambiguous because the choice of start vs end timestamp, and the freq anchor, changes the answer; pandas refuses and points the user at to_timestamp(how='start').mean().","triggerScenarios":"Calling period_idx.mean() or period_series.mean(); dispatched into the EA mean override at line 1574; the PeriodDtype check at line 1574 raises.","commonSituations":"Resampling/aggregating Period-indexed data; porting DatetimeIndex pipelines to PeriodIndex; calling .describe() or .groupby().mean() on Period columns.","solutions":["Convert to timestamp first as the message suggests: idx.to_timestamp(how='start').mean() (or how='end').","For integer-meaningful aggregation, average the ordinals: int(idx.view('i8').mean()) then reconstruct a Period.","If grouping, group on the Period column but aggregate a numeric column, not the Period itself.","For resampling, use .to_timestamp() then resample and convert back with .to_period(freq)."],"exampleFix":"// before\nm = period_idx.mean()  # TypeError: mean is not implemented\n// after\nm = period_idx.to_timestamp(how='start').mean()","handlingStrategy":"type-guard","validationCode":"from pandas.api.types import is_period_dtype\nif is_period_dtype(idx.dtype):\n    m = idx.to_timestamp(how='start').mean()\nelse:\n    m = idx.mean()","typeGuard":"def rejects_direct_mean(idx) -> bool:\n    from pandas.api.types import is_period_dtype\n    return is_period_dtype(idx.dtype)","tryCatchPattern":"try:\n    m = idx.mean()\nexcept TypeError as e:\n    if 'mean is not implemented' in str(e):\n        m = idx.to_timestamp(how='start').mean()\n    else:\n        raise","preventionTips":["Convert PeriodIndex to timestamp before .mean().","Aggregate numeric columns, not Period columns, in groupby .mean().","Allow-list reductions per dtype."],"tags":["reduction","mean","period","ambiguous"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}