Pandas Tutorial Pandas References

Pandas Series - prod() function



The Pandas Series prod() function returns the product of the values over the specified axis. The syntax for using this function is mentioned below:

Syntax

Series.prod(axis=None, skipna=None, level=None, 
            numeric_only=None, min_count=0)

Parameters

axis Optional. Specify {0 or 'index'}. Specify axis for the function to be applied on.
skipna Optional. Specify True to exclude NA/null values when computing the result. Default is True.
level Optional. Specify level (int or str). If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a scalar. A str specifies the level name.
numeric_only Optional. Specify True to include only float, int or boolean data. Default: False
min_count Optional. Specify required number of valid values to perform the operation. If the count of non-NA values is less than the min_count, the result will be NA.

Return Value

Returns scalar or Series if a level is specified.

Example: using prod() on a Series

In the example below, the prod() function is used to get the product of values of a given series.

import pandas as pd
import numpy as np

idx = pd.MultiIndex.from_arrays([
    ['Sample1', 'Sample1', 'Sample1', 
     'Sample2', 'Sample2', 'Sample2']],
    names=['DataType'])

x = pd.Series([1, 2, 3, 11, 12, 13], 
              name='Numbers', index=idx)

print("The Series contains:")
print(x)

#product of all values in the series
print("\nx.prod() returns:")
print(x.prod())

#product of all values within given level
print("\nx.prod(level='DataType') returns:")
print(x.prod(level='DataType'))
print("\nx.prod(level=0) returns:")
print(x.prod(level=0))

The output of the above code will be:

The Series contains:
DataType
Sample1      1
Sample1      2
Sample1      3
Sample2     11
Sample2     12
Sample2     13
Name: Numbers, dtype: int64

x.prod() returns:
10296

x.prod(level='DataType') returns:
DataType
Sample1       6
Sample2    1716
Name: Numbers, dtype: int64

x.prod(level=0) returns:
DataType
Sample1       6
Sample2    1716
Name: Numbers, dtype: int64

Example: using prod() on selected series in a DataFrame

Similarly, the prod() function can be applied on selected series/column of a given DataFrame. Consider the following example.

import pandas as pd
import numpy as np

df = pd.DataFrame({
  "Sample1": [1, 2, 3, 4, 5],
  "Sample2": [11, 12, 13, 14, 15],
  "Sample3": [9, 8, 7, 6, 5]},
  index= ["x1", "x2", "x3", "x4", "x5"]
)

print("The DataFrame is:")
print(df)

#product of values of 'Sample3' series
print("\ndf['Sample3'].prod() returns:")
print(df["Sample3"].prod())

The output of the above code will be:

The DataFrame is:
    Sample1  Sample2  Sample3
x1        1       11        9
x2        2       12        8
x3        3       13        7
x4        4       14        6
x5        5       15        5

df['Sample3'].prod() returns:
15120

❮ Pandas Series - Functions