Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pandas
python

How to obtain the product of the values over a DataFrame's axis

Onyejiaku Theophilus Chidalu

Overview

In pandas, the prod() function is used to obtain the product of the values of a specified axis of the given DataFrame.

Syntax

The prod() function takes the syntax shown below:

DataFrame.prod(axis=NoDefault.no_default, skipna=True, numeric_only=None, min_count=0, **kwargs)
Syntax for the prod() function in Pandas

Parameters

The prod() function takes the following optional parameter values:

  • axis: This represents the name for the row (designated as 0 or 'index') or the column (designated as 1 or columns) axis.
  • skipna: This takes a Boolean value indicating if NA or null values are to be excluded or not.
  • numeric_only: This takes a Boolean value indicating if we want to include only float, int, and Boolean columns.
  • min_count: This takes an int value depicting the required number of valid values to perform the product operation.
  • **kwargs: This is an additional keyword argument that can be passed to the function.

Code example

Let's look at the code below:

# A code to illustrate the prod() function in Pandas

# importing the pandas library
import pandas as pd

# creating a dataframe
df = pd.DataFrame([[1,2,3,4,5],
                   [1,7,5,9,0.5],
                   [3,11,13,14,12]],
                   columns=list('ABCDE'))
# printing the dataframe
print(df)

# obtaining the product of the values vertically across rows
print(df.prod())

# obtaining the product of the values horizontally over columns
print(df.prod(axis="columns"))
Implementing the prod() function

Code explanation

  • Line 4: We import the pandas library.
  • Lines 7 to 10: We create a DataFrame, df.
  • Line 12: We print the DataFrame, df.
  • Line 15: We use the prod() function to obtain the product of values running downwards across the rows (axis 0). We print the result to the console.
  • Line 18: We use the prod() function to obtain the product of values running horizontally across columns (axis 1). We print the result to the console.

RELATED TAGS

pandas
python

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring