pandas-dev/pandas · error · TypeError

cannot add Period to a {type(self).__name__}

Error message

cannot add Period to a {type(self).__name__}

What it means

Raised by _add_period when a Period scalar is added to an array whose dtype is not timedelta (kind != 'm'). Only TimedeltaArray + Period is defined (yielding PeriodArray); DatetimeArray + Period and PeriodArray + Period are rejected.

Source

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

        from pandas.core.arrays import TimedeltaArray

        try:
            self._assert_tzawareness_compat(other)
        except TypeError as err:
            new_message = str(err).replace("compare", "subtract")
            raise type(err)(new_message) from err

        other_i8, o_mask = self._get_i8_values_and_mask(other)
        res_values = add_overflowsafe(self.asi8, np.asarray(-other_i8, dtype="i8"))
        res_m8 = res_values.view(f"timedelta64[{self.unit}]")

        return TimedeltaArray._simple_new(res_m8, dtype=res_m8.dtype)

    @final
    def _add_period(self, other: Period) -> PeriodArray:
        if not lib.is_np_dtype(self.dtype, "m"):
            raise TypeError(f"cannot add Period to a {type(self).__name__}")

        # We will wrap in a PeriodArray and defer to the reversed operation
        from pandas.core.arrays.period import PeriodArray

        i8vals = np.broadcast_to(other.ordinal, self.shape)
        dtype = PeriodDtype(other.freq)
        parr = PeriodArray(i8vals, dtype=dtype)
        return parr + self

    def _add_offset(self, offset):
        raise AbstractMethodError(self)

    def _add_timedeltalike_scalar(self, other):
        """
        Add a delta of a timedeltalike

        Returns
        -------

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Convert the Period to a Timedelta via its freq if you meant a duration: pd.tseries.frequencies.to_offset(period.freq) * period.
  2. Add a DateOffset (e.g. pd.DateOffset(months=1)) instead of a Period to a DatetimeIndex.
  3. For PeriodIndex, shift via idx + n (integer) or idx.shift(n) instead of adding a Period.
  4. Verify self.dtype.kind == 'm' before adding a Period.

Example fix

// before
out = datetime_idx + pd.Period('2020-01', 'M')  # TypeError
// after
out = datetime_idx + pd.DateOffset(months=1)
Defensive patterns

Strategy: type-guard

Validate before calling

if idx.dtype.kind != 'm':
    # cannot add Period; convert to DateOffset
    other = pd.DateOffset(months=1)
out = idx + other

Type guard

def accepts_period_addition(idx) -> bool:
    return getattr(idx.dtype, 'kind', None) == 'm'

Try / catch

try:
    out = idx + period
except TypeError as e:
    if 'cannot add Period' in str(e):
        out = idx + pd.DateOffset(months=period.n)
    else:
        raise

Prevention

When it happens

Trigger: DatetimeIndex + pd.Period(...) or PeriodIndex + pd.Period(...), dispatched via __add__ line 1326-1327 (only entered when self is timedelta dtype) — for non-timedelta, the call still reaches _add_period through other paths and fails at line 1139.

Common situations: Mixing Period and datetime columns in arithmetic; treating a Period like a DateOffset.

Related errors


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