Search code examples
pythonpandastime-serieslag

Lag pandas time series on nearest date


I have a time series as below:

enter image description here

I would like to lag column A by one month by choosing the nearest value to (t - 1 Mth).

For example, A', being the lagged column A, would have for row 1991-02-27, the value corresponding to 1991-01-30.

What would be the Pandas solution for this?


Solution

  • You can simplify one month lag by 30 days lag and use reindex with parameter method='nearest':

    df = df.reindex(df.index - pd.to_timedelta(30, unit='d'), method='nearest')