polars.Expr.shift
-
Shift values by the given number of indices.
- Parameters:
-
- n
-
Number of indices to shift forward. If a negative value is passed, values are shifted in the opposite direction instead.
- fill_value
-
Fill the resulting null values with this scalar value.
See also
Notes
This method is similar to the
LAGoperation in SQL when the value fornis positive. With a negative value forn, it is similar toLEAD.Examples
By default, values are shifted forward by one index.
>>> df = pl.DataFrame({"a": [1, 2, 3, 4]}) >>> df.with_columns(shift=pl.col("a").shift()) shape: (4, 2) ┌─────┬───────┐ │ a ┆ shift │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪═══════╡ │ 1 ┆ null │ │ 2 ┆ 1 │ │ 3 ┆ 2 │ │ 4 ┆ 3 │ └─────┴───────┘Pass a negative value to shift in the opposite direction instead.
>>> df.with_columns(shift=pl.col("a").shift(-2)) shape: (4, 2) ┌─────┬───────┐ │ a ┆ shift │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪═══════╡ │ 1 ┆ 3 │ │ 2 ┆ 4 │ │ 3 ┆ null │ │ 4 ┆ null │ └─────┴───────┘Specify
fill_valueto fill the resulting null values.>>> df.with_columns(shift=pl.col("a").shift(-2, fill_value=100)) shape: (4, 2) ┌─────┬───────┐ │ a ┆ shift │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪═══════╡ │ 1 ┆ 3 │ │ 2 ┆ 4 │ │ 3 ┆ 100 │ │ 4 ┆ 100 │ └─────┴───────┘
Expr.shift(
n: int | IntoExprColumn = 1,
*,
fill_value: IntoExpr | None = None,
) → Expr
© 2020 Ritchie Vink
© 2022 Polars contributors
Licensed under the MIT License.
https://docs.pola.rs/api/python/stable/reference/expressions/api/polars.Expr.shift.html