Creating Lag Features in Pandas Using Shift

Python

 1|  # each value of previous_row is the value from 
 2|  # the previous row of col_A
 3|  df['previous_row'] = df['col_A'].shift(periods=1)
 4|  
 5|  # each value of next_row is the value from the next row of col_A
 6|  df['next_row'] = df['col_A'].shift(periods=-1)
 7|  
 8|  # get the value of close from the previous row, grouped by stock 
 9|  df['close_yesterday'] = df.groupby(['stock'])['close'].shift(periods=1)
10|  
11|  # get the value of close from the next row, grouped by stock 
12|  df['close_tomorrow'] = df.groupby(['stock'])['close'].shift(periods=-1)
Did you find this snippet useful?

Sign up for free to to add this to your code library