• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / Python / pandas cumprod – Find Cumulative Product of Series or DataFrame

pandas cumprod – Find Cumulative Product of Series or DataFrame

January 19, 2022 Leave a Comment

To calculate the cumulative product over columns in a DataFrame, or the cumulative product of the values of a Series in pandas, the easiest way is to use the pandas cumsum() function.

df.cumprod() # Calculate cumulative product for all columns
df["Column"].cumprod() #calculate cumulative productfor 1 column

You can also use the numpy cumprod() function to calculate the cumulative product for a column or Series.

np.cumprod(df["Column"])

When working with data, many times we want to calculate summary statistics to understand our data better. One such statistic is the cumulative product, or the multiplicative total of a list of numbers after each element of the list.

Finding the cumulative productof a column, or the cumulative product for all columns or rows in a DataFrame using pandas is easy. We can use the pandas cumprod() function to find the cumulative product of a column of numbers, or for all columns or rows in a DataFrame.

Let’s say we have the following DataFrame.

df = pd.DataFrame({'Age': [43,23,71,49,52,37], 
      'Test_Score':[90,87,92,96,84,79]})

print(df)
# Output: 
   Age  Test_Score
0   43          90
1   23          87
2   71          92
3   49          96
4   52          84
5   37          79

To get the cumulative product for all columns, we can call the pandas cumprod() function.

print(df.cumsum())

# Output:
          Age    Test_Score
0          43            90
1         989          7830
2       70219        720360
3     3440731      69154560
4   178918012    5808983040
5  6619966444  458909660160

If we only want to get the cumulative product of just one column, we can do this using the pandas cumprod() function in the following Python code:

print(df["Test_Score"].cumprod())

# Output:
0              90
1            7830
2          720360
3        69154560
4      5808983040
5    458909660160
Name: Test_Score, dtype: int64

Calculating the Cumulative Product by Row in pandas DataFrame

We can also calculate the cumulative product by row by pass “axis=1” to the cumprod() function.

Below is how to find the cumulative product across the rows of a pandas DataFrame using the same DataFrame from above.

print(df.cumprod(axis=1))

# Output:
   Age  Test_Score
0   43        3870
1   23        2001
2   71        6532
3   49        4704
4   52        4368
5   37        2923

Calculating the Cumulative Product of a Column With Missing Values

As many of us know, when working with data, sometimes we have to work with messy data or data with missing values. Let’s take our DataFrame from above and add a few NaN values.

df = pd.DataFrame({'Age': [43,np.NaN,71,49,np.NaN,37], 
      'Test_Score':[90,87,92,np.NaN,84,79]})

print(df)
# Output: 
    Age  Test_Score
0  43.0        90.0
1   NaN        87.0
2  71.0        92.0
3  49.0         NaN
4   NaN        84.0
5  37.0        79.0

If you want to calculate the cumulative product of a column with missing values, by default, the cumprod() function will ignore those missing values.

print(df.cumprod())

# Output:
     Age  Test_Score
0       43.0  9.000000e+01
1        NaN  7.830000e+03
2     3053.0  7.203600e+05
3   149597.0           NaN
4        NaN  6.051024e+07
5  5535089.0  4.780309e+09

If you want the cumprod() function to include the NaN values in the product operation, you can pass “skipna=False”.

print(df.cumprod(skipna=False))

# Output:
    Age  Test_Score
0  43.0        90.0
1   NaN      7830.0
2   NaN    720360.0
3   NaN         NaN
4   NaN         NaN
5   NaN         NaN

Using the numpy cumprod() Function to Calculate Cumulative Product of a Column

We can also use the numpy cumprod() function to calculate the cumulative product of a column in a pandas DataFrame.

Let’s say we have the same dataset from above.

To get the cumulative product of the numbers in the column “Test_Score”, we can use the numpy cumprod() function in the following Python code:

print(np.cumprod(df["Test_Score"]))

# Output:
0              90
1            7830
2          720360
3        69154560
4      5808983040
5    458909660160
Name: Test_Score, dtype: int64

As you can see above, this is the same value we received from the pandas cumprod() function.

Hopefully this article has been helpful for you to understand how to find the cumulative product of numbers in a Series or columns in a DataFrame in pandas.

Other Articles You'll Also Like:

  • 1.  Using Python to Replace Backslash in String
  • 2.  pandas ewm – Calculate Exponentially Weighted Statistics in DataFrame
  • 3.  Open Multiple Files Using with open in Python
  • 4.  Convert timedelta to Seconds in Python
  • 5.  Using readlines() and strip() to Remove Spaces and \n from File in Python
  • 6.  Change Python Turtle Shape Fill Color with fillcolor() Function
  • 7.  Using Python to Print Environment Variables
  • 8.  Using Selenium to Get Text from Element in Python
  • 9.  How to Check if Tuple is Empty in Python
  • 10.  Convert String into Tuple in Python

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy