datatable.shift()

Produce a column obtained from col shifting it n rows forward.

The shift amount, n, can be both positive and negative. If positive, a “lag” column is created, if negative it will be a “lead” column.

The shifted column will have the same number of rows as the original column, with n observations in the beginning becoming missing, and n observations at the end discarded.

This function is group-aware, i.e. in the presence of a groupby it will perform the shift separately within each group.

Examples

from datatable import dt, f, by DT = dt.Frame({"object": [1, 1, 1, 2, 2], "period": [1, 2, 4, 4, 23], "value": [24, 67, 89, 5, 23]}) DT
objectperiodvalue
int32int32int32
01124
11267
21489
3245
422323

Shift forward - Create a “lag” column:

DT[:, dt.shift(f.period, n = 3)]
period
int32
0NA
1NA
2NA
31
42

Shift backwards - Create “lead” columns:

DT[:, dt.shift(f[:], n = -3)]
objectperiodvalue
int32int32int32
0245
122323
2NANANA
3NANANA
4NANANA

Shift in the presence of by():

DT[:, f[:].extend({"prev_value": dt.shift(f.value)}), by("object")]
objectperiodvalueprev_value
int32int32int32int32
01124NA
1126724
2148967
3245NA
4223235