Pandas DataFrame prod() and product() Method


Preparation

Before any data manipulation can occur, two (2) new libraries will require installation.

  • The Pandas library enables access to/from a DataFrame.
  • The NumPy library supports multi-dimensional arrays and matrices in addition to a collection of mathematical functions.

To install these libraries, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install numpy

Hit the <Enter> key on the keyboard to start the installation process.

If the installations were successful, a message displays in the terminal indicating the same.


Feel free to view the PyCharm installation guide for the required libraries.


Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import pandas as pd
import numpy as np 

DataFrame prod() and product()

The prod() and product() methods are identical. Both return the product of the values of a requested axis.

The syntax for these methods is as follows:

DataFrame.prod(axis=None, skipna=None, level=None, numeric_only=None, min_count=0, **kwargs)
DataFrame.product(axis=None, skipna=None, level=None, numeric_only=None, min_count=0, **kwargs)
ParameterDescription
axisIf zero (0) or index is selected, apply to each column. Default 0.
If one (1) apply to each row.
skipnaIf set to True, this parameter excludes NaN/NULL values when calculating the result.
levelSet the appropriate parameter if the DataFrame/Series is multi-level. If no value, then None is assumed.
numeric_onlyOnly include columns that contain integers, floats, or boolean values.
min_countThe number of values on which to perform the calculation.
**kwargsAdditional keywords are passed into a DataFrame/Series.

For this example, random numbers generate, and the product on the selected axis returns.

df = pd.DataFrame({'A':   [2, 4, 6],
                   'B':   [7, 3, 5],
                   'C':   [6, 3, 1]})
                   
index_ = ['A', 'B', 'C']
df.index = index_

result = df.prod(axis=0)
print(result)
  • Line [1] creates a DataFrame complete with random numbers and saves it to df.
  • Line [2-3] creates and sets the DataFrame index.
  • Line [3] calculates the product along axis 0. This output saves to the result variable.
  • Line [4] outputs the result to the terminal.

Output

Formula Example: 2*4*6=48

A48
B105
C18
dtype: int64

More Pandas DataFrame Methods

Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:

Also, check out the full cheat sheet overview of all Pandas DataFrame methods.