In Polars, the sum() function is used to compute the sum of values across a DataFrame’s columns or within a specific column. This function performs a column-wise summation, adding the values within each column. It works similarly to sum() in Pandas but is optimized for performance in Polars. In this article, I will explain how to sum Polars DataFrame rows for given columns with examples.
Key Points –
- Use
sum()to compute the sum of values in one or more columns of a Polars DataFrame. - You can sum a single column by specifying its name within
pl.sum("column_name"). - You can sum multiple specific columns by passing a list to
pl.sum(["col1", "col2"]). - Apply
pl.col("column_name").sum()insideselect()to sum individual or multiple columns. - Calling
sum()on a DataFrame sums all numeric columns, ignoring non-numeric ones. - By default,
sum()ignores null values. Use.fill_null(0)to replace them before summation. - Use
pl.sum_horizontal(["col1", "col2"])to sum multiple columns for each row instead of column-wise aggregation. - Use
with_columns((pl.col("col1") + pl.col("col2")).alias("Total"))to create new columns with summed values.
<a id="h-polars-dataframe-sum-introduction"></a>
Polars DataFrame sum() Introduction
Let’s know the syntax of the Polars DataFrame sum() function.
# Syntax of sum()
polars.sum(*names: str) → Expr
<a id="h-parameters-of-the-polars-dataframe-sum"></a>
Parameters of the Polars DataFrame.sum()
*names- One or more column names whose values will be summed.
<a id="h-return-value"></a>
Return Value
This function returns an expression (Expr) that can be used in select(), with_columns(), or pl.sum_horizontal() function
<a id="h-usage-of-polars-sum-dataframe-columns"></a>
Usage of Polars Sum DataFrame Columns
The sum() function in Polars is used to compute the total sum of values in one or multiple columns of a DataFrame. It efficiently handles numerical data while ignoring null values by default.
To run some examples of the Polars sum DataFrame columns, let’s create a Polars DataFrame.
import polars as pl
studentdetails = {
"Studentname":["Ram", "Sam", "Scott", "Ann", "John"],
"Mathematics" :[80,90,85,72,95],
"Science" :[85,95,80,90,92],
"English" :[90,85,80,75,95]
}
df = pl.DataFrame(studentdetails)
print("Original DataFrame:\n", df)
Yields below output.
The sum() function calculates the sum of numeric columns while excluding non-numeric ones (such as strings) in polars. This makes it especially useful for aggregating numerical data such as total scores, financial metrics, or other quantitative datasets.
# Using sum() to calculate column-wise sum
df2 = df.sum()
print("Column-wise Sum:\n", df2)
Here,
- The
"Studentname"column (which is non-numeric) is ignored. - Polars computes the sum for each numeric column. Mathematics:
80 + 90 + 85 + 72 + 95 = 422. Science:85 + 95 + 80 + 90 + 92 = 442. English:90 + 85 + 80 + 75 + 95 = 425. - The output is a single-row DataFrame where each column contains the sum of its values.
<a id="h-summing-a-specific-column-using-select"></a>
Summing a Specific Column Using select()
If you want to compute the sum of a specific column, you can use the select() function along with sum() method. The select() function allows you to apply operations on specific columns and return a new DataFrame rather than modifying the original one.
# Sum of only the "Mathematics" column
df2 = df.select(pl.col("Mathematics").sum())
print("Sum of Mathematics column:\n", df2)
# Summing a specific column (Mathematics)
df2 = df.select(pl.sum("Mathematics"))
print("Sum of Mathematics column:\n", df2)
# Output:
# Sum of Mathematics column:
# shape: (1, 1)
┌─────────────┐
│ Mathematics │
│ --- │
│ i64 │
╞═════════════╡
│ 422 │
└─────────────┘
Here,
df.select(pl.col("Mathematics").sum())selects only the"Mathematics"column and calculates its sum.- This method ensures only one column is summed while keeping the DataFrame format.
- This returns the sum of only the
"Mathematics"column.
<a id="h-using-sum-on-multiple-columns"></a>
Using sum() on Multiple Columns
To sum multiple specific columns in a Polars DataFrame, you can pass multiple column names to the pl.sum() function.
# Summing "Mathematics" and "Science" columns
df2 = df.select(pl.sum(["Mathematics", "Science"]))
print("Sum of Mathematics & Science columns:\n", df2)
# Output:
# Sum of Mathematics & Science columns:
# shape: (1, 2)
┌─────────────┬─────────┐
│ Mathematics ┆ Science │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════════════╪═════════╡
│ 422 ┆ 442 │
└─────────────┴─────────┘
Here,
select()extracts only the specified columns.sum()computes the sum of each selected column.- This computes the sum for only the specified columns (
"Mathematics"and"Science").
<a id="h-row-wise-sum-using-sum-horizontal"></a>
Row-wise Sum Using sum_horizontal()
You can calculate the sum of multiple columns for each row using the sum_horizontal() function. This is useful when computing total scores for each student, summing financial transactions per record, or aggregating any numerical data across columns.
Let's calculate the total marks by summing the Mathematics, Science, and English scores for each student.
# Adding a Total Score column
df = df.with_columns(
pl.sum_horizontal("Mathematics", "Science", "English").alias("Total Score"))
print(df)
# Output:
# shape: (5, 5)
┌─────────────┬─────────────┬─────────┬─────────┬─────────────┐
│ Studentname ┆ Mathematics ┆ Science ┆ English ┆ Total Score │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 ┆ i64 ┆ i64 │
╞═════════════╪═════════════╪═════════╪═════════╪═════════════╡
│ Ram ┆ 80 ┆ 85 ┆ 90 ┆ 255 │
│ Sam ┆ 90 ┆ 95 ┆ 85 ┆ 270 │
│ Scott ┆ 85 ┆ 80 ┆ 80 ┆ 245 │
│ Ann ┆ 72 ┆ 90 ┆ 75 ┆ 237 │
│ John ┆ 95 ┆ 92 ┆ 95 ┆ 282 │
└─────────────┴─────────────┴─────────┴─────────┴─────────────┘
Here,
pl.sum_horizontal("Mathematics", "Science", "English")computes the sum for each row..alias("Total Score")renames the result to"Total Score".with_columns()adds the calculated sum as a new column to the DataFrame.
<a id="h-sum-after-filtering-based-on-a-condition"></a>
Sum After Filtering Based on a Condition
You can first filter the DataFrame based on a specific condition and then apply the sum() function to sum the relevant numeric columns. This is useful for scenarios such as calculating total scores for students who meet a certain criterion or aggregating sales data for specific categories.
# Filtering students with Science > 80 and summing Mathematics scores
df2 = df.filter(pl.col("Science") > 80).select(pl.col("Mathematics").sum())
print(df2)
# Output:
# shape: (1, 1)
┌─────────────┐
│ Mathematics │
│ --- │
│ i64 │
╞═════════════╡
│ 337 │
└─────────────┘
Here,
filter(pl.col("Science") > 80)selects students scoring more than 80 in Science.select(pl.col("Mathematics").sum())calculates the sum of Mathematics scores for the filtered students.
<a id="h-sum-with-missing-values-nulls"></a>
Sum with missing values (Nulls)
When using sum() in Polars, missing values (nulls) can affect the results. By default, Polars ignores null values when summing. Let's explore how sum() behaves with missing data.
import polars as pl
# Creating a DataFrame with null (missing) values
studentdetails = {
"Studentname": ["Ram", "Sam", "Scott", "Ann", "John"],
"Mathematics": [80, 90, None, 72, 95],
"Science": [85, None, 80, 90, 92],
"English": [90, 85, 80, 75, None]
}
df = pl.DataFrame(studentdetails)
# Sum of all numeric columns
print(df.sum())
# Output:
# shape: (1, 4)
┌─────────────┬─────────────┬─────────┬─────────┐
│ Studentname ┆ Mathematics ┆ Science ┆ English │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 ┆ i64 │
╞═════════════╪═════════════╪═════════╪═════════╡
│ null ┆ 337 ┆ 347 ┆ 330 │
└─────────────┴─────────────┴─────────┴─────────┘
By default, sum() ignores nulls when calculating sums. However, if you want to replace None values with 0 before summing, you can use fill_null(0).
# Handling missing values
df2 = df.fill_null(0).sum()
print(df2)
# Output:
# shape: (1, 4)
┌─────────────┬─────────────┬─────────┬─────────┐
│ Studentname ┆ Mathematics ┆ Science ┆ English │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 ┆ i64 │
╞═════════════╪═════════════╪═════════╪═════════╡
│ null ┆ 337 ┆ 347 ┆ 330 │
└─────────────┴─────────────┴─────────┴─────────┘
<a id="h-conclusion"></a>
Conclusion
In this article, I have explained how to compute the sum of Polars DataFrame columns whether for all columns, specific columns, or on a row-wise basis by using the df.sum() function, select() function, pl.sum_horizontal(), and df.with_columns() function in Polars.
Happy Learning!!
<a id="h-related-articles"></a>
Related Articles
- Polars DataFrame row() Usage & Examples
- Polars DataFrame count() Function
- Polars DataFrame limit() Method
- Polars DataFrame median() Usage & Examples
- Polars DataFrame std() – Usage & Examples
- Polars DataFrame tail() – Usage & Examples
- Polars DataFrame update() – Usage & Examples
- Polars.DataFrame.mean() – Explained by Examples
- Polars DataFrame partition_by() Usage & Examples
<a id="h-references"></a>
