In Python, the pandas
library includes built-in functionalities that allow you to perform different tasks with only a few lines of code. One of these functionalities is the creation of lags and leads of a column.
lag
shifts a column down by a certain number.lead
shifts a column up by a certain number.ID |
1 |
2 |
3 |
4 |
5 |
6 |
ID | Leads 1 | Lags 1 |
1 | 2 | NaN |
2 | 3 | 1 |
3 | 4 | 2 |
4 | 5 | 3 |
5 | 6 | 4 |
6 | NaN | 5 |
In this method, we first initialize a pandas
dataframe with a numpy
array as input. Then we select a column and apply lead
and lag
by shifting that column up and down, respectively.
#importing pandas and numpy librariesimport pandas as pdimport numpy as np#initializing pandas dataframe with numpy arraysdf = pd.DataFrame(np.random.randint(1, 100, 10).reshape(-1, 2), columns = list('ab'))#applying leads and lags by shifting dataframe column up and down respectivelydf['lag(a,1)'] = df['a'].shift(1)df['lag(a,5)'] = df['a'].shift(5)df['lead(b,2)'] = df['b'].shift(-2)df['lead(b,4)'] = df['b'].shift(-4)print(df)