Skip to content

Commit c9fd73a

Browse files
jbrockmendelAlexKirko
authored andcommitted
BUG: DTA/TDA/PA iadd/isub should actually be inplace (pandas-dev#30505)
1 parent 20f51b7 commit c9fd73a

File tree

3 files changed

+28
-6
lines changed

3 files changed

+28
-6
lines changed

doc/source/whatsnew/v1.0.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -717,7 +717,7 @@ Datetimelike
717717
- Bug in :class:`DatetimeIndex` addition when adding a non-optimized :class:`DateOffset` incorrectly dropping timezone information (:issue:`30336`)
718718
- Bug in :meth:`DataFrame.drop` where attempting to drop non-existent values from a DatetimeIndex would yield a confusing error message (:issue:`30399`)
719719
- Bug in :meth:`DataFrame.append` would remove the timezone-awareness of new data (:issue:`30238`)
720-
720+
- Bug in :class:`DatetimeArray`, :class:`TimedeltaArray`, and :class:`PeriodArray` where inplace addition and subtraction did not actually operate inplace (:issue:`24115`)
721721

722722
Timedelta
723723
^^^^^^^^^

pandas/core/arrays/datetimelike.py

+14-5
Original file line numberDiff line numberDiff line change
@@ -1311,14 +1311,23 @@ def __rsub__(self, other):
13111311

13121312
return -(self - other)
13131313

1314-
# FIXME: DTA/TDA/PA inplace methods should actually be inplace, GH#24115
13151314
def __iadd__(self, other): # type: ignore
1316-
# alias for __add__
1317-
return self.__add__(other)
1315+
result = self + other
1316+
self[:] = result[:]
1317+
1318+
if not is_period_dtype(self):
1319+
# restore freq, which is invalidated by setitem
1320+
self._freq = result._freq
1321+
return self
13181322

13191323
def __isub__(self, other): # type: ignore
1320-
# alias for __sub__
1321-
return self.__sub__(other)
1324+
result = self - other
1325+
self[:] = result[:]
1326+
1327+
if not is_period_dtype(self):
1328+
# restore freq, which is invalidated by setitem
1329+
self._freq = result._freq
1330+
return self
13221331

13231332
# --------------------------------------------------------------
13241333
# Comparison Methods

pandas/tests/arrays/test_datetimelike.py

+13
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,19 @@ def test_setitem_raises(self):
225225
with pytest.raises(TypeError, match="'value' should be a.* 'object'"):
226226
arr[0] = object()
227227

228+
def test_inplace_arithmetic(self):
229+
# GH#24115 check that iadd and isub are actually in-place
230+
data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
231+
arr = self.array_cls(data, freq="D")
232+
233+
expected = arr + pd.Timedelta(days=1)
234+
arr += pd.Timedelta(days=1)
235+
tm.assert_equal(arr, expected)
236+
237+
expected = arr - pd.Timedelta(days=1)
238+
arr -= pd.Timedelta(days=1)
239+
tm.assert_equal(arr, expected)
240+
228241

229242
class TestDatetimeArray(SharedTests):
230243
index_cls = pd.DatetimeIndex

0 commit comments

Comments
 (0)