Home:ALL Converter>pandas: creating lagged variables of existing variable in a loop

pandas: creating lagged variables of existing variable in a loop

Ask Time:2017-12-24T11:23:17         Author:Zenvega

Json Formatter

I have a dataframe df with multiple time series variables. Say variable 'A', 'B', 'C' etc.

There have date as the index. How can I create 3,6 and 12 month lagged version in a loop? I guess I could manually type for each variable like below, but was hoping if there is an efficient way to do it. Thanks.

df['A_3'] = df['A'].shift(3)
df['A_6'] = df['A'].shift(6)
df['A_12'] = df['A'].shift(12)

df['B_3'] = df['B'].shift(3)
df['B_6'] = df['B'].shift(6)
df['B_12'] = df['B'].shift(12)

Author:Zenvega,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/47957818/pandas-creating-lagged-variables-of-existing-variable-in-a-loop
yy