In Polars, the product() function is used to compute the product of values in a column or across multiple columns of a DataFrame. This is similar to the prod() function in Pandas. By default, this function processes numeric values and computes the product of all values in the specified column. It returns a single-row DataFrame containing the product of each column's values.
In this article, I will discuss the Polars DataFrame product() function, covering its syntax, parameters, and usage. I will also explain how to generate a single-row DataFrame containing the computed product values, while non-numeric columns are automatically ignored.
Key Points –
- The
product()function calculates the product of all numerical values in a column. - You can apply
product()insideselect()to compute the product of one or multiple columns. - You can calculate the product for multiple columns by passing multiple expressions inside
select(). - It operates only on integer (
i64) and float (f64) columns, ignoring non-numeric data. - Filtering
(filter()) can be applied before calculating the product to focus on specific rows. - If a column contains null values, they can be handled using
fill_null(), asproduct()ignores them by default. - Polars'
product()function is optimized for speed, making it faster than traditional Pandas operations. - Non-destructive operation, meaning it does not modify the original DataFrame but returns a new one.
<a id="h-syntax-of-polars-dataframe-product-function"></a>
Syntax of Polars DataFrame product() Function
Let’s know the syntax of the product() function.
# Syntax of polars product()
DataFrame.product() → DataFrame
<a id="h-parameters-of-the-polars-dataframe-product"></a>
Parameters of the Polars DataFrame.product()
Computes the cumulative product of each numeric column.
<a id="h-return-value"></a>
Return Value
This function returns a single-row DataFrame with the computed product values. Non-numeric columns are ignored.
<a id="h-usage-of-polars-dataframe-product-function"></a>
Usage of Polars DataFrame product() Function
The product() function in Polars computes the multiplicative product of all values in each column of a DataFrame. It multiplies all non-null values in a column and returns a single-row DataFrame with the results.
Now, let’s create a Polars DataFrame.
import polars as pl
# Sample DataFrame
df = pl.DataFrame({
'A': [2, 4, 6, 8],
'B': [3, 5, 7, 9],
'C': [1, 2, 3, 4]
})
print("Original DataFrame:\n",df)
Yields below output.
To compute the product of a single column in your Polars DataFrame, use the select() function along with the product() method.
# Compute the product of column 'A'
result = df.select(pl.col("A").product())
print("Product of column 'A':\n", result)
# Compute product of column 'A'
result = df["A"].product()
print("Product of column A:", result)
Here,
- The product is computed as, 2×4×6×8=384
<a id="h-compute-product-of-all-columns"></a>
Compute Product of All Columns
The product() method in Polars computes the cumulative product of all numeric columns in a DataFrame using its default parameters.
# Compute product of all columns
result = df.product()
print("Product of all columns:\n", result)
# Output:
# Product of all columns:
# shape: (1, 3)
┌─────┬─────┬─────┐
│ A ┆ B ┆ C │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ 384 ┆ 945 ┆ 24 │
└─────┴─────┴─────┘
Here,
Each column’s product is calculated separately
- Column A: 2 × 4 × 6 × 8 = 384
- Column B: 3 × 5 × 7 × 9 = 945
- Column C: 1 × 2 × 3 × 4 = 24
<a id="h-compute-product-for-multiple-columns"></a>
Compute Product for Multiple Columns
If you want to compute the product of specific columns, you can use the select() method and specify the column names with the product() function.
import polars as pl
# Sample DataFrame
df = pl.DataFrame({
'A': [2, 4, 6, 8],
'B': [3, 5, 7, 9],
'C': [1, 2, 3, 4],
'D': ["x", "y", "z", "w"] # Non-numeric column
})
# Compute the product for specific columns ('A' and 'B')
result = df.select([
pl.col("A").product().alias("A_product"),
pl.col("B").product().alias("B_product")])
print("Product of selected columns:\n", result)
# Output:
# Product of selected columns:
# shape: (1, 2)
┌───────────┬───────────┐
│ A_product ┆ B_product │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═══════════╪═══════════╡
│ 384 ┆ 945 │
└───────────┴───────────┘
Here,
- Column 'A' Product: 2×4×6×8=384
- Column 'B' Product: 3×5×7×9=945
The product() function is applied only to columns 'A' and 'B', ignoring column 'C' and non-numeric column 'D'.
<a id="h-selective-column-product"></a>
Selective Column Product
If you want to compute the product of specific columns, you can use select() with pl.col(). This allows you to apply product() only to chosen columns while ignoring others.
# Compute product only for columns 'A' and 'C'
result = df.select([
pl.col("A").product().alias("A_product"),
pl.col("C").product().alias("C_product")])
print("Product of selected columns:\n", result)
# Output:
# Product of selected columns:
# shape: (1, 2)
┌───────────┬───────────┐
│ A_product ┆ C_product │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═══════════╪═══════════╡
│ 384 ┆ 24 │
└───────────┴───────────┘
Here,
- Selecting specific columns (
AandC) before applyingproduct(). - Ignoring other columns (
BandDare not included). - Computing products separately for selected columns:
- A: 2 × 4 × 6 × 8 = 384
- C: 1 × 2 × 3 × 4 = 24
<a id="h-using-product-with-filters"></a>
Using product() with Filters
You can apply filters before computing the product using the filter() method. This allows you to calculate the product only for specific rows that meet a given condition.
import polars as pl
# Sample DataFrame
df = pl.DataFrame({
'A': [2, 4, 6, 8],
'B': [3, 5, 7, 9],
'C': [1, 2, 3, 4]
})
# Compute the product of column 'A' where 'B' > 4
result = df.filter(pl.col("B") > 4).select(pl.col("A").product())
print("Product of column 'A' where B > 4:\n", result)
# Output:
# Product of column 'A' where B > 4:
# shape: (1, 1)
┌─────┐
│ A │
│ --- │
│ i64 │
╞═════╡
│ 192 │
└─────┘
<a id="h-handling-missing-values-null"></a>
Handling Missing Values (null)
When computing the product in Polars, missing values (null) can affect the result. Polars provides options to handle them. By default, if a column contains null values, the result for that column will be null.
import polars as pl
# Sample DataFrame with null values
df = pl.DataFrame({
'A': [2, 4, None, 8],
'B': [3, None, 7, 9],
'C': [1, 2, 3, 4]
})
# Compute product
result = df.product()
print("Product with null handling:\n", result)
# Output:
# Product with null handling:
# shape: (1, 3)
┌─────┬─────┬─────┐
│ A ┆ B ┆ C │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ 64 ┆ 189 ┆ 24 │
└─────┴─────┴─────┘
When computing the product in Polars, null values can cause the result to be null. To avoid this issue, we can replace null with 1 (neutral in multiplication) using fill_null(1).
# Replace nulls with 1 before computing product
result = df.fill_null(1).product()
print("Product with nulls replaced:\n", result)
# Output:
# Product with nulls replaced:
# shape: (1, 3)
┌─────┬─────┬─────┐
│ A ┆ B ┆ C │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ 64 ┆ 189 ┆ 24 │
└─────┴─────┴─────┘
Here,
- Original Data (Column
A&Bcontain null) - Replacing null with 1 before computing the product,
- A: 2 × 4 × 1 × 8 = 64
- B: 3 × 1 × 7 × 9 = 189
- C: 1 × 2 × 3 × 4 = 24 (unchanged since no nulls)
- Returns a new DataFrame with
nullvalues handled properly.
<a id="h-conclusion"></a>
Conclusion
In this article, I have explained the Polars DataFrame product() method by using its syntax, parameters, usage, and how we can return a single-row DataFrame containing the product of each column.
Happy Learning!!
<a id="h-related-articles"></a>
Related Articles
- Polars DataFrame count() Function
- Select Polars Columns by Index
- Convert Polars Cast Integer to Float
- Convert Polars Cast Float to Integer
- Polars Sum Multiple Columns
- Polars DataFrame row() Usage & Examples
- Polars DataFrame median() Usage & Examples
- Polars DataFrame std() – Usage & Examples
- Append or Concatenate Two DataFrames in Polars
- Polars.DataFrame.mean() – Explained by Examples
- Polars DataFrame partition_by() Usage & Examples
<a id="h-references"></a>
