Shift each group by periods observations.
If freq is passed, the index will be increased using the periods and the freq.
Number of periods to shift. If a list of values, shift each group by each period.
Frequency string.
Shift direction.
Deprecated since version 2.1.0: For axis=1, operate on the underlying object instead. Otherwise the axis keyword is not necessary.
The scalar value to use for newly introduced missing values.
Changed in version 2.1.0: Will raise a ValueError if freq is provided too.
A string to add to each shifted column if there are multiple periods. Ignored otherwise.
Object shifted within each group.
See also
Index.shiftShift values of Index.
Examples
For SeriesGroupBy:
>>> lst = ['a', 'a', 'b', 'b']
>>> ser = pd.Series([1, 2, 3, 4], index=lst)
>>> ser
a 1
a 2
b 3
b 4
dtype: int64
>>> ser.groupby(level=0).shift(1)
a NaN
a 1.0
b NaN
b 3.0
dtype: float64
For DataFrameGroupBy:
>>> data = [[1, 2, 3], [1, 5, 6], [2, 5, 8], [2, 6, 9]]
>>> df = pd.DataFrame(data, columns=["a", "b", "c"],
... index=["tuna", "salmon", "catfish", "goldfish"])
>>> df
a b c
tuna 1 2 3
salmon 1 5 6
catfish 2 5 8
goldfish 2 6 9
>>> df.groupby("a").shift(1)
b c
tuna NaN NaN
salmon 2.0 3.0
catfish NaN NaN
goldfish 5.0 8.0
© 2008–2011, AQR Capital Management, LLC, Lambda Foundry, Inc. and PyData Development Team
© 2011–2025, Open source contributors
Licensed under the 3-clause BSD License.
https://pandas.pydata.org/pandas-docs/version/2.3.0/reference/api/pandas.core.groupby.SeriesGroupBy.shift.html