To find the product of the values in columns in a DataFrame, or the product of the values of a Series in pandas, the easiest way is to use the pandas prod() function.
df.prod() # Calculate products for all columns
df["Column"].prod() #calculate product for 1 column
The pandas product() function is equivalent to the pandas prod() function.
You can also use the numpy prod() function.
np.prod(df["Column"]) #calculate sum for 1 column
When working with data, many times we want to calculate summary statistics to understand our data better. One such statistic is the product, or the multiplicative total of a list of numbers.
Finding the product of a column, or the product for all columns in a DataFrame using pandas is easy. We can use the pandas prod() function to find the total of a column of numbers, or 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 product for all columns, we can call the pandas prod() function.
print(df.prod())
# Output:
Age 6619966444
Test_Score 458909660160
dtype: int64
If we only want to get the product of just one column, we can do this using the pandas prod() function in the following Python code:
print(df["Test_Score"].prod())
# Output:
458909660160
If you want to see how the product is calculated step by step, you can use the pandas cumprod() function and return a Series for each column with the cumulative product at each point.
Using numpy prod to Calculate a Product in pandas DataFrame
We can also use the numpy prod() function to calculate the product of the numbers in a column in a pandas DataFrame.
To get the product of the numbers in the column “Test_Score”, we can use the numpy prod() function in the following Python code:
print(np.prod(df["Test_Score"]))
# Output:
458909660160
As you can see above, this is the same value we received from the pandas prod() function.
Hopefully this article has been helpful for you to understand how to find the product of numbers in a Series or DataFrame in pandas.