Column total
Select a single aggregate total from a DataFrame column.
Polars · Function
polars.sum creates an expression that sums all values in one or more named columns. It is shorthand for col(name).sum() and supports multiple names or a regular-expression selector.
pl.sum constructs an expression that aggregates every value in one or more named columns. It is shorthand for selecting each column with pl.col(name).sum(), and it can also accept a regular-expression selector to choose matching columns.
polars.sum(**names: str) → Expr| Name | Type | Description |
|---|---|---|
names | str | Name or names of the columns to use in the aggregation. |
Expr
import polars as pl
df = pl.DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]})
result = df.select(pl.sum("a", "c"))
print(result)Builds an expression that sums columns a and c, then evaluates it with select.
Select a single aggregate total from a DataFrame column.
Compute independent totals for several numeric columns in one select operation.
Choose columns by a naming pattern when the schema is dynamic.
pl.sum returns an Expr representing a column aggregation, rather than immediately computing a Python scalar. A single column name is equivalent to pl.col(name).sum().
Follow-up: How would you preserve null for an all-null column? Use pl.when(pl.col(name).count()>0).then(pl.sum(name)).otherwise(None).then(pl.sum(name)) is not required; the documented pattern uses the count condition around the sum.
Pass multiple column names to create one result per named column. The documented examples also show a regular-expression selector such as pl.sum("^.*[bc]$") to select matching columns.
Follow-up: When should a row-wise operation be used instead? Use pl.sum_horizontal for horizontal aggregation across columns in each row.
The function sums all values in the selected columns and returns an Expr. If a selected column contains no non-null values, its result is 0.
Follow-up: What alternative is documented for empty sums? Wrap the sum in a count check so the expression returns None when the non-null count is zero.
polars.Expr.sumpolars.Series.sumpolars.sum_horizontal