
In Polars, standard aggregations (sum, mean) work vertically (down a column). But what if you want to sum across columns? For this, the Polars fold operation is extremely useful. e.g., total_score = math_score + science_score + history_score + ... If you have 3 columns, you can just use +. But if you have 50 columns, you need fold().
The Syntax
fold(accumulator, function, columns) It works like a “reduce” function. It starts with an accumulator (usually 0) and applies a function to each column in the list, adding it to the total.
The Setup
import polars as pl
df = pl.DataFrame({
"id": [1, 2],
"jan": [10, 20],
"feb": [15, 25],
"mar": [30, 10]
})Summing Horizontal Columns
Let’s create a total_q1 column by summing Jan, Feb, and Mar.
df_total = df.with_columns(
pl.fold(
acc=pl.lit(0), # Start at 0
function=lambda acc, x: acc + x, # Add column x to accumulator
exprs=[pl.col("jan"), pl.col("feb"), pl.col("mar")] # Columns to fold
).alias("total_q1")
)
print(df_total)The Pro Move: Select by Regex
You don’t have to list every column manually! Use a selector.
import polars.selectors as cs
# Sum ALL numeric columns (except 'id')
df_auto = df.with_columns(
pl.sum_horizontal(pl.exclude("id")).alias("grand_total")
)
# Note: pl.sum_horizontal() is a modern shortcut for the common 'sum' fold!Use fold() for complex custom logic, and sum_horizontal() / max_horizontal() for simple math.
Key Takeaways
- In Polars, standard aggregations work vertically, but you can sum across columns using fold().
- The syntax for fold() is fold(accumulator, function, columns), which acts like a reduce function.
- Create new columns by summing multiple existing columns, like total_q1 for Jan, Feb, and Mar.
- You can simplify column selection with a selector instead of listing every column manually.
- For complex logic, use fold(); for straightforward calculations, use sum_horizontal() or max_horizontal().





