Method: Polars::Functions#fold

Defined in:
lib/polars/functions/lazy.rb

#fold(acc, exprs, returns_scalar: false, return_dtype: nil, &function) ⇒ Expr

Accumulate over multiple columns horizontally/row wise with a left fold.

Examples:

Horizontally sum over all columns and add 1.

df = Polars::DataFrame.new(
 {
   "a" => [1, 2, 3],
   "b" => [3, 4, 5],
   "c" => [5, 6, 7]
 }
)
df.select(
  Polars.fold(Polars.lit(1), Polars.col("*")) { |acc, x| acc + x }.alias("sum")
)
# =>
# shape: (3, 1)
# ┌─────┐
# │ sum │
# │ --- │
# │ i32 │
# ╞═════╡
# │ 10  │
# │ 13  │
# │ 16  │
# └─────┘

You can also apply a condition/predicate on all columns:

df = Polars::DataFrame.new(
  {
    "a" => [1, 2, 3],
    "b" => [0, 1, 2]
  }
)
df.filter(
  Polars.fold(Polars.lit(true), Polars.col("*") > 1) { |acc, x| acc & x }
)
# =>
# shape: (1, 2)
# ┌─────┬─────┐
# │ a   ┆ b   │
# │ --- ┆ --- │
# │ i64 ┆ i64 │
# ╞═════╪═════╡
# │ 3   ┆ 2   │
# └─────┴─────┘

Returns:



1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
# File 'lib/polars/functions/lazy.rb', line 1078

def fold(
  acc,
  exprs,
  returns_scalar: false,
  return_dtype: nil,
  &function
)
  acc = Utils.parse_into_expression(acc, str_as_lit: true)
  if exprs.is_a?(Expr)
    exprs = [exprs]
  end

  rt = nil
  if !return_dtype.nil?
    rt = Utils.parse_into_datatype_expr(return_dtype)._rbdatatype_expr
  end

  exprs = Utils.parse_into_list_of_expressions(exprs)
  Utils.wrap_expr(
    Plr.fold(
      acc,
      _wrap_acc_lambda(function),
      exprs,
      returns_scalar,
      rt
    )
  )
end