Skip to content

Commit 03bbcb0

Browse files
authored
REGR: DataFrame.shift with periods>len(columns) GH#44978 (#45005)
1 parent 0a8ae44 commit 03bbcb0

File tree

3 files changed

+16
-2
lines changed

3 files changed

+16
-2
lines changed

doc/source/whatsnew/v1.4.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -878,6 +878,7 @@ Other
878878
- Bug in :meth:`Series.replace` and :meth:`DataFrame.replace` with ``value=None`` and ExtensionDtypes (:issue:`44270`,:issue:`37899`)
879879
- Bug in :meth:`FloatingArray.equals` failing to consider two arrays equal if they contain ``np.nan`` values (:issue:`44382`)
880880
- Bug in :meth:`DataFrame.shift` with ``axis=1`` and ``ExtensionDtype`` columns incorrectly raising when an incompatible ``fill_value`` is passed (:issue:`44564`)
881+
- Bug in :meth:`DataFrame.shift` with ``axis=1`` and ``periods`` larger than ``len(frame.columns)`` producing an invalid :class:`DataFrame` (:issue:`44978`)
881882
- Bug in :meth:`DataFrame.diff` when passing a NumPy integer object instead of an ``int`` object (:issue:`44572`)
882883
- Bug in :meth:`Series.replace` raising ``ValueError`` when using ``regex=True`` with a :class:`Series` containing ``np.nan`` values (:issue:`43344`)
883884
- Bug in :meth:`DataFrame.to_records` where an incorrect ``n`` was used when missing names were replaced by ``level_n`` (:issue:`44818`)

pandas/core/internals/managers.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -388,12 +388,13 @@ def shift(self: T, periods: int, axis: int, fill_value) -> T:
388388
# GH#35488 we need to watch out for multi-block cases
389389
# We only get here with fill_value not-lib.no_default
390390
ncols = self.shape[0]
391+
nper = abs(periods)
392+
nper = min(nper, ncols)
391393
if periods > 0:
392394
indexer = np.array(
393-
[-1] * periods + list(range(ncols - periods)), dtype=np.intp
395+
[-1] * nper + list(range(ncols - periods)), dtype=np.intp
394396
)
395397
else:
396-
nper = abs(periods)
397398
indexer = np.array(
398399
list(range(nper, ncols)) + [-1] * nper, dtype=np.intp
399400
)

pandas/tests/frame/methods/test_shift.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -664,3 +664,15 @@ def test_shift_axis1_categorical_columns(self):
664664
columns=ci,
665665
)
666666
tm.assert_frame_equal(result, expected)
667+
668+
@td.skip_array_manager_not_yet_implemented
669+
def test_shift_axis1_many_periods(self):
670+
# GH#44978 periods > len(columns)
671+
df = DataFrame(np.random.rand(5, 3))
672+
shifted = df.shift(6, axis=1, fill_value=None)
673+
674+
expected = df * np.nan
675+
tm.assert_frame_equal(shifted, expected)
676+
677+
shifted2 = df.shift(-6, axis=1, fill_value=None)
678+
tm.assert_frame_equal(shifted2, expected)

0 commit comments

Comments
 (0)