Groupby-shift, save column

Viewed 38

I try to save column on which I groupby when shifting

pd.DataFrame({'column1':['Alex', 'Bob', 'Bob'], 'column2':[3, 4, 5]}).groupby('column1').shift(1)

I want the final dataframe to have 'Alex', 'Bob' and 'Bob' in the index

1 Answers

You can add the shifted values to your existing dataframe:

df = pd.DataFrame({'column1':['Alex', 'Bob', 'Bob'], 'column2':[3, 4, 5]})
df['shift']  = df.groupby(['column1']).shift(1)
df = df.set_index('column1')
Related