From 6daa9446f9a1f3982496412c081acbafc719a546 Mon Sep 17 00:00:00 2001 From: jbrockmendel Date: Thu, 26 Mar 2020 20:25:47 -0700 Subject: [PATCH 1/2] REF: avoid internals in tshift --- pandas/core/generic.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index b9ce7cce3685c..a1770ad369c10 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -8978,7 +8978,7 @@ def slice_shift(self: FrameOrSeries, periods: int = 1, axis=0) -> FrameOrSeries: return new_obj.__finalize__(self) def tshift( - self: FrameOrSeries, periods: int = 1, freq=None, axis=0 + self: FrameOrSeries, periods: int = 1, freq=None, axis: Axis = 0 ) -> FrameOrSeries: """ Shift the time index, using the index's frequency if available. @@ -9020,22 +9020,21 @@ def tshift( if isinstance(freq, str): freq = to_offset(freq) - block_axis = self._get_block_manager_axis(axis) + axis = self._get_axis_number(axis) if isinstance(index, PeriodIndex): orig_freq = to_offset(index.freq) - if freq == orig_freq: - new_data = self._data.copy() - new_data.axes[block_axis] = index.shift(periods) - elif orig_freq is not None: + if freq != orig_freq: raise ValueError( f"Given freq {freq.rule_code} does not match " f"PeriodIndex freq {orig_freq.rule_code}" ) + new_ax = index.shift(periods) else: - new_data = self._data.copy() - new_data.axes[block_axis] = index.shift(periods, freq) + new_ax = index.shift(periods, freq) - return self._constructor(new_data).__finalize__(self) + result = self.copy() + result.set_axis(new_ax, axis, inplace=True) + return result.__finalize__(self) def truncate( self: FrameOrSeries, before=None, after=None, axis=None, copy: bool_t = True From 96d98da917679a149d5bd19b4a5d5f0054484c60 Mon Sep 17 00:00:00 2001 From: jbrockmendel Date: Thu, 26 Mar 2020 21:03:27 -0700 Subject: [PATCH 2/2] mypy fixup --- pandas/core/generic.py | 1 + 1 file changed, 1 insertion(+) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index a1770ad369c10..fef292306e741 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -9024,6 +9024,7 @@ def tshift( if isinstance(index, PeriodIndex): orig_freq = to_offset(index.freq) if freq != orig_freq: + assert orig_freq is not None # for mypy raise ValueError( f"Given freq {freq.rule_code} does not match " f"PeriodIndex freq {orig_freq.rule_code}"