What is the DataFrame.product() function in Polars?

The polars.DataFrame.product() function is used to aggregate the columns of a DataFrame to their product values. This function calculates the product of all elements in each column and returns a new DataFrame with a single row containing the product values for each column.

Syntax

Here’s the syntax of the product() function:

DataFrame.product()

The resulting DataFrame will have a single row, with the product of each column as its values:

Code

We will use the product() function, to check its functionality in Polars. For this, we will take four columns named as p1, p2, p3, and p4. Each of them contains different values.

import polars as pl
df= pl.DataFrame(
{
"p1": [5, 10, 3, 2, 9],
"p2": [48, 0.5, 7, 4, 0.2],
"p3": [True, False, True, True, False],
"p4": [7, 9, 34, 2, 1],
}
)
result = df.product();
print (result)

Explanation

We will now explain the above code step by step:

  • Lines 3–11: We created a DataFrame (df) using the Polars library. The DataFrame has four columns (p1, p2, p3, p4) with corresponding data. p1 and p4 contain integer values, p2 contains floating-point values, and p3 contains boolean values.

  • Line 12: We use the product() function, the product function will calculate the product of each column:

    • p1: The product of the values in the column (5 * 10 * 3 * 2 * 9) is 2700.

    • p2: The product of the values in the column (48 * 0.5 * 7 * 4 * 0.2) is 134.0.

    • p3: The product of the boolean values in the column (True * False * True * True * False) is false. In this way, True is considered as 1 and False as 0.

    • p4: The product of the values in this column is (7 * 9 * 34 * 2 * 1) is 4284.

  • Line 13: We printed the result. It will show a newly generated DataFrame consisting of a single row that displays the product values for each column.

The polars.DataFrame.product() function aggregates the columns within a DataFrame by computing their product values. Subsequently, it generates a new DataFrame presenting a single row that encapsulates these calculated product values for each column.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved