Open In App

Find the geometric mean of a given Pandas DataFrame

In this article, we will discuss how to find the geometric mean of a given DataFrame. Generally geometric mean of nth numbers is the nth root of their product.



It can found using the scipy.stats.gmean() method. This function calculates the geometric mean of the array elements along the specified axis of the array (list in python).

Syntax:



scipy.stats.gmean(array, axis=0, dtype=None)

Approach :

Step-by-Step Implementation :

Step 1: Importing module and Making Dataframe.




# importing module
import pandas as pd
import numpy as np
from scipy import stats
  
# Create a DataFrame
df = pd.DataFrame({
    'Name': ['Monty', 'Anurag', 'Kavya', 'Hunny', 'Saurabh',
             'Shubham', 'Ujjawal', 'Satyam', 'Prity', 'Tanya'
             'Amir', 'donald'],
    'Match1_score': [52, 87, 35, 14, 41, 71, 95, 83, 22, 82, 11, 97],
    'match2_score': [45, 80, 62, 53, 49, 82, 36, 97, 84, 93, 39, 59]})
  
# Display DataFrame
df

Output :

Step 2:  Create an empty DataFrame column.




# Creating empty column in DataFrame
df['Geometric Mean'] = None
df

Output :

Step 3: Find Geometric mean with scipy.stats.gmean()  and store it into a new column.




# Computing geometric mean
# Storing into a DataFrame column
df['Geometric Mean'] = stats.gmean(df.iloc[:, 1:3], axis=1)
df

Output :


Article Tags :