Skip to content

Cumulative sum

Source code

Description

Get an array with the cumulative sum computed at every element.

Usage

<Expr>$cum_sum(reverse = FALSE)

Arguments

reverse If TRUE, start with the total sum of elements and substract each row one by one.

Details

The Dtypes Int8, UInt8, Int16 and UInt16 are cast to Int64 before summing to prevent overflow issues.

Value

Expr

Examples

library("polars")

pl$DataFrame(a = 1:4)$with_columns(
  pl$col("a")$cum_sum()$alias("cum_sum"),
  pl$col("a")$cum_sum(reverse = TRUE)$alias("cum_sum_reversed")
)
#> shape: (4, 3)
#> ┌─────┬─────────┬──────────────────┐
#> │ a   ┆ cum_sum ┆ cum_sum_reversed │
#> │ --- ┆ ---     ┆ ---              │
#> │ i32 ┆ i32     ┆ i32              │
#> ╞═════╪═════════╪══════════════════╡
#> │ 1   ┆ 1       ┆ 10               │
#> │ 2   ┆ 3       ┆ 9                │
#> │ 3   ┆ 6       ┆ 7                │
#> │ 4   ┆ 10      ┆ 4                │
#> └─────┴─────────┴──────────────────┘