Pandas: Shift down values by one row within a group

Newer versions of pandas can now perform a shift on a group:

df['B_shifted'] = df.groupby(['A'])['B'].shift(1)

Note that when shifting down, it’s the first row that has NaN.

Leave a Comment