Skip to content

Computes percentage change between values

Description

Computes the percentage change (as fraction) between current element and most-recent non-null element at least n period(s) before the current element. By default it computes the change from the previous row.

Usage

<Expr>$pct_change(n = 1)

Arguments

n Integer or Expr indicating the number of periods to shift for forming percent change.

Value

A polars expression

Examples

library("polars")

df <- pl$DataFrame(a = c(10:12, NA, 12))
df$with_columns(
  pct_change = pl$col("a")$pct_change()
)
#> shape: (5, 2)
#> ┌──────┬────────────┐
#> │ a    ┆ pct_change │
#> │ ---  ┆ ---        │
#> │ f64  ┆ f64        │
#> ╞══════╪════════════╡
#> │ 10.0 ┆ null       │
#> │ 11.0 ┆ 0.1        │
#> │ 12.0 ┆ 0.090909   │
#> │ null ┆ 0.0        │
#> │ 12.0 ┆ 0.0        │
#> └──────┴────────────┘