如何改进 LAG 功能?

How can I improve the LAG function?

我有以下 table:

time comsales indsales
1 20.96 127.3
2 21.4 130
3 21.96 132.7
4 21.52 129.4
5 22.39 135
6 22.76 137.1
7 23.48 141.2
8 23.66 142.8
9 24.1 145.5
10 24.01 145.3
11 24.54 148.3
12 24.3 146.4
13 25 150.2
14 25.64 153.1
15 26.36 157.3
16 26.98 160.7
17 27.52 164.2
18 27.78 165.6
19 28.24 168.7
20 28.78 171.7

我正在尝试使用以下代码在 python 中实现 LAG 函数

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm

dataset = pd.read_csv('Data/blaisdellcomp.csv', index_col=0)
y = dataset['comsales']
x = dataset['indsales']

X = sm.add_constant(x)
model = sm.OLS(y, X).fit()
print(model.summary())

residuals = model.resid
residuals = residuals.reset_index(drop=True)

lagged_residuals = residuals.rolling(1).sum()
lagged_residuals.drop(lagged_residuals.tail(1).index,inplace=True)
lagged_residuals.loc[-1] = lagged_residuals[0]  # adding a row
lagged_residuals.index = lagged_residuals.index + 1  # shifting index
lagged_residuals.sort_index(inplace=True)
lagged_residuals = lagged_residuals.reset_index(drop=True)

为了能够在残差中产生滞后,我使用了很多代码来实现滞后。有没有更好的方法来实现残差的滞后?

您似乎在寻找 Pandas shift 方法:

lagged_residuals = residuals.shift(1)