diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst index 578e24009d35a..ec0a5565b582d 100644 --- a/doc/source/whatsnew/v0.25.0.rst +++ b/doc/source/whatsnew/v0.25.0.rst @@ -276,6 +276,7 @@ Datetimelike - Improved :class:`Timestamp` type checking in various datetime functions to prevent exceptions when using a subclassed ``datetime`` (:issue:`25851`) - Bug in :class:`Series` and :class:`DataFrame` repr where ``np.datetime64('NaT')`` and ``np.timedelta64('NaT')`` with ``dtype=object`` would be represented as ``NaN`` (:issue:`25445`) - Bug in :func:`to_datetime` which does not replace the invalid argument with ``NaT`` when error is set to coerce (:issue:`26122`) +- Bug in adding :class:`DateOffset` with nonzero month to :class:`DatetimeIndex` would raise ``ValueError`` (:issue:`26258`) Timedelta ^^^^^^^^^ diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index e383f47cf010d..910fa4818c5de 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -1435,6 +1435,28 @@ def test_dt64arr_add_sub_offset_ndarray(self, tz_naive_fixture, expected = tm.box_expected(expected, box_with_array) tm.assert_equal(res, expected) + @pytest.mark.parametrize("op, offset, exp", [ + ('__add__', pd.DateOffset(months=3, days=10), + DatetimeIndex([Timestamp('2014-04-11'), Timestamp('2015-04-11'), + Timestamp('2016-04-11'), Timestamp('2017-04-11')])), + ('__add__', pd.DateOffset(months=3), + DatetimeIndex([Timestamp('2014-04-01'), Timestamp('2015-04-01'), + Timestamp('2016-04-01'), Timestamp('2017-04-01')])), + ('__sub__', pd.DateOffset(months=3, days=10), + DatetimeIndex([Timestamp('2013-09-21'), Timestamp('2014-09-21'), + Timestamp('2015-09-21'), Timestamp('2016-09-21')])), + ('__sub__', pd.DateOffset(months=3), + DatetimeIndex([Timestamp('2013-10-01'), Timestamp('2014-10-01'), + Timestamp('2015-10-01'), Timestamp('2016-10-01')])) + + ]) + def test_dti_add_sub_nonzero_mth_offset(self, op, offset, exp): + # GH 26258 + date = date_range(start='01 Jan 2014', end='01 Jan 2017', freq='AS') + mth = getattr(date, op) + result = mth(offset) + tm.assert_equal(result, exp) + class TestDatetime64OverflowHandling: # TODO: box + de-duplicate diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index 9900ad1a1f4af..29fee48f85015 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -273,7 +273,7 @@ def apply_index(self, i): kwds.get('months', 0)) * self.n) if months: shifted = liboffsets.shift_months(i.asi8, months) - i = type(i)(shifted, freq=i.freq, dtype=i.dtype) + i = type(i)(shifted, dtype=i.dtype) weeks = (kwds.get('weeks', 0)) * self.n if weeks: