In this handbook is an example how to utilise the function polars::prelude::fold_exprs
to accumulate the row values over multiple columns horizontally.
let df = df!(
"a" => &[1, 2, 3],
"b" => &[10, 20, 30],
)?;
let out = df
.lazy()
.select([fold_exprs(lit(0), |acc, x| Ok(Some(acc + x)), [col("*")]).alias("sum")])
.collect()?;
println!("{}", out);
The output is:
shape: (3, 1)
┌─────┐
│ sum │
│ --- │
│ i64 │
╞═════╡
│ 11 │
│ 22 │
│ 33 │
└─────┘
Question: How can I accumulate the row values over the single column col(b)
vertically using the fold_exprs
function to get the following output:
shape: (3, 1)
┌─────┐
│ sum │
│ --- │
│ i64 │
╞═════╡
│ 10 │
│ 30 │
│ 60 │
└─────┘
I'm looking for something like:
let out = df
.lazy()
.select([fold_exprs(lit(0), |acc, x| Ok(Some(acc + x)), [col("b")]).alias("sum")])
.collect()?;
where I replaced col("*")
with col("b")
: How do I have to modify the closure |acc, x| Ok(Some(acc + x))
to get my desired output?