Skip to content

Commit d765dfb

Browse files
AaronCritchleyjreback
authored andcommitted
API: Make .shift always copy (Fixes pandas-dev#22397) (pandas-dev#22517)
1 parent 307797c commit d765dfb

File tree

4 files changed

+22
-2
lines changed

4 files changed

+22
-2
lines changed

doc/source/whatsnew/v0.24.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -544,6 +544,7 @@ Other API Changes
544544
- :class:`Index` subtraction will attempt to operate element-wise instead of raising ``TypeError`` (:issue:`19369`)
545545
- :class:`pandas.io.formats.style.Styler` supports a ``number-format`` property when using :meth:`~pandas.io.formats.style.Styler.to_excel` (:issue:`22015`)
546546
- :meth:`DataFrame.corr` and :meth:`Series.corr` now raise a ``ValueError`` along with a helpful error message instead of a ``KeyError`` when supplied with an invalid method (:issue:`22298`)
547+
- :meth:`shift` will now always return a copy, instead of the previous behaviour of returning self when shifting by 0 (:issue:`22397`)
547548

548549
.. _whatsnew_0240.deprecations:
549550

pandas/core/arrays/datetimelike.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -548,7 +548,7 @@ def shift(self, n, freq=None):
548548

549549
if n == 0:
550550
# immutable so OK
551-
return self
551+
return self.copy()
552552

553553
if self.freq is None:
554554
raise NullFrequencyError("Cannot shift with no freq")

pandas/core/generic.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -8282,7 +8282,7 @@ def mask(self, cond, other=np.nan, inplace=False, axis=None, level=None,
82828282
@Appender(_shared_docs['shift'] % _shared_doc_kwargs)
82838283
def shift(self, periods=1, freq=None, axis=0):
82848284
if periods == 0:
8285-
return self
8285+
return self.copy()
82868286

82878287
block_axis = self._get_block_manager_axis(axis)
82888288
if freq is None:

pandas/tests/generic/test_series.py

+19
Original file line numberDiff line numberDiff line change
@@ -227,3 +227,22 @@ def test_valid_deprecated(self):
227227
# GH18800
228228
with tm.assert_produces_warning(FutureWarning):
229229
pd.Series([]).valid()
230+
231+
@pytest.mark.parametrize("s", [
232+
Series([np.arange(5)]),
233+
pd.date_range('1/1/2011', periods=24, freq='H'),
234+
pd.Series(range(5), index=pd.date_range("2017", periods=5))
235+
])
236+
@pytest.mark.parametrize("shift_size", [0, 1, 2])
237+
def test_shift_always_copy(self, s, shift_size):
238+
# GH22397
239+
assert s.shift(shift_size) is not s
240+
241+
@pytest.mark.parametrize("move_by_freq", [
242+
pd.Timedelta('1D'),
243+
pd.Timedelta('1M'),
244+
])
245+
def test_datetime_shift_always_copy(self, move_by_freq):
246+
# GH22397
247+
s = pd.Series(range(5), index=pd.date_range("2017", periods=5))
248+
assert s.shift(freq=move_by_freq) is not s

0 commit comments

Comments
 (0)