From 9a3c75dc8fd3ad127a3621ceeffde3283d8913d0 Mon Sep 17 00:00:00 2001 From: Brock Date: Thu, 15 Dec 2022 11:41:12 -0800 Subject: [PATCH] BUG: Index[offset_objects] + Period --- doc/source/whatsnew/v2.0.0.rst | 1 + pandas/_libs/tslibs/period.pyx | 16 ++++++++++++++++ pandas/tests/arithmetic/test_object.py | 12 ++++++++++++ 3 files changed, 29 insertions(+) diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 0b29843735189..f89a6e4cb0a27 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -876,6 +876,7 @@ I/O Period ^^^^^^ - Bug in :meth:`Period.strftime` and :meth:`PeriodIndex.strftime`, raising ``UnicodeDecodeError`` when a locale-specific directive was passed (:issue:`46319`) +- Bug in adding a :class:`Period` object to an array of :class:`DateOffset` objects incorrectly raising ``TypeError`` (:issue:`50162`) - Plotting diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 86fa965be92c4..8955fb678d075 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1741,6 +1741,11 @@ cdef class _Period(PeriodMixin): raise TypeError(f"unsupported operand type(s) for +: '{sname}' " f"and '{oname}'") + elif util.is_array(other): + if other.dtype == object: + # GH#50162 + return np.array([self + x for x in other], dtype=object) + return NotImplemented def __radd__(self, other): @@ -1767,11 +1772,22 @@ cdef class _Period(PeriodMixin): elif other is NaT: return NaT + elif util.is_array(other): + if other.dtype == object: + # GH#50162 + return np.array([self - x for x in other], dtype=object) + return NotImplemented def __rsub__(self, other): if other is NaT: return NaT + + elif util.is_array(other): + if other.dtype == object: + # GH#50162 + return np.array([x - self for x in other], dtype=object) + return NotImplemented def asfreq(self, freq, how="E") -> "Period": diff --git a/pandas/tests/arithmetic/test_object.py b/pandas/tests/arithmetic/test_object.py index cba2b9be255fb..b94816687ecca 100644 --- a/pandas/tests/arithmetic/test_object.py +++ b/pandas/tests/arithmetic/test_object.py @@ -73,6 +73,18 @@ def test_more_na_comparisons(self, dtype): class TestArithmetic: + def test_add_period_to_array_of_offset(self): + # GH#50162 + per = pd.Period("2012-1-1", freq="D") + pi = pd.period_range("2012-1-1", periods=10, freq="D") + idx = per - pi + + expected = pd.Index([x + per for x in idx], dtype=object) + result = idx + per + tm.assert_index_equal(result, expected) + + result = per + idx + tm.assert_index_equal(result, expected) # TODO: parametrize def test_pow_ops_object(self):