datatable.shift()¶
Shift columns’ data forward or backwards. This function is group-aware, i.e. in the presence of a groupby it will shift data separately within each group.
Parameters¶
cols
FExpr
Input data to be shifted.
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
object | period | value | ||
---|---|---|---|---|
int32 | int32 | int32 | ||
0 | 1 | 1 | 24 | |
1 | 1 | 2 | 67 | |
2 | 1 | 4 | 89 | |
3 | 2 | 4 | 5 | |
4 | 2 | 23 | 23 |
Shift forward by creating a “lag” column:
DT[:, dt.shift(f.period, n = 3)]
period | ||
---|---|---|
int32 | ||
0 | NA | |
1 | NA | |
2 | NA | |
3 | 1 | |
4 | 2 |
Shift backwards by creating “lead” columns:
DT[:, dt.shift(f[:], n = -3)]
object | period | value | ||
---|---|---|---|---|
int32 | int32 | int32 | ||
0 | 2 | 4 | 5 | |
1 | 2 | 23 | 23 | |
2 | NA | NA | NA | |
3 | NA | NA | NA | |
4 | NA | NA | NA |
Shift within groups, i.e. in the presence of by()
:
DT[:, f[:].extend({"prev_value": dt.shift(f.value)}), by("object")]
object | period | value | prev_value | ||
---|---|---|---|---|---|
int32 | int32 | int32 | int32 | ||
0 | 1 | 1 | 24 | NA | |
1 | 1 | 2 | 67 | 24 | |
2 | 1 | 4 | 89 | 67 | |
3 | 2 | 4 | 5 | NA | |
4 | 2 | 23 | 23 | 5 |
The content on this page is licensed under the Creative Commons Attribution 4.0 License
(CC BY 4.0) ,
and code samples are licensed under the MIT License.