Skip to content

Shift a DataFrame

Source code

Description

Shift the values by a given period. If the period (n) is positive, then n rows will be inserted at the top of the DataFrame and the last n rows will be discarded. Vice-versa if the period is negative. In the end, the total number of rows of the DataFrame doesn’t change.

Usage

<DataFrame>$shift(n = 1, fill_value = NULL)

Arguments

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 value. Accepts expression input. Non-expression inputs are parsed as literals.

Value

DataFrame

Examples

library("polars")

df = pl$DataFrame(a = 1:4, b = 5:8)

df$shift(2)
#> shape: (4, 2)
#> ┌──────┬──────┐
#> │ a    ┆ b    │
#> │ ---  ┆ ---  │
#> │ i32  ┆ i32  │
#> ╞══════╪══════╡
#> │ null ┆ null │
#> │ null ┆ null │
#> │ 1    ┆ 5    │
#> │ 2    ┆ 6    │
#> └──────┴──────┘
df$shift(-2)
#> shape: (4, 2)
#> ┌──────┬──────┐
#> │ a    ┆ b    │
#> │ ---  ┆ ---  │
#> │ i32  ┆ i32  │
#> ╞══════╪══════╡
#> │ 3    ┆ 7    │
#> │ 4    ┆ 8    │
#> │ null ┆ null │
#> │ null ┆ null │
#> └──────┴──────┘
df$shift(-2, fill_value = 100)
#> shape: (4, 2)
#> ┌───────┬───────┐
#> │ a     ┆ b     │
#> │ ---   ┆ ---   │
#> │ f64   ┆ f64   │
#> ╞═══════╪═══════╡
#> │ 3.0   ┆ 7.0   │
#> │ 4.0   ┆ 8.0   │
#> │ 100.0 ┆ 100.0 │
#> │ 100.0 ┆ 100.0 │
#> └───────┴───────┘