In this short guide, you’ll see how to calculate the geometric mean in Python.
3 Ways to Calculate the Geometric Mean in Python
In the sections below, you’ll observe 3 ways to calculate the geometric mean in Python. For each of the methods to be reviewed, the goal is to derive the geometric mean, given the following values:
8, 16, 22, 12, 41
Method 1: Simple Calculations to get the Geometric Mean
To start, you can use the following calculations to get the geometric mean:
multiply_values = 8*16*22*12*41 n = 5 geometric_mean = (multiply_values)**(1/n) print ('The Geometric Mean is: ' + str(geometric_mean))
Where:
- multiply_values represents the multiplication of all the values in the dataset
- n reflects the number of items in the dataset. In our example, there are 5 items
- geometric_mean = (multiply_values)**(1/n) is the actual calculation to derive the geometric mean
Run the code in Python, and you’ll get the following result: 16.9168
Method 2: Using a List to Derive the Geometric Mean in Python
Alternatively, you can place all the values in a list, where each value should be separated by a comma:
multiply = 1 values = [8,16,22,12,41] n = len(values) for i in values: multiply = (multiply)*(i) geometric_mean = (multiply)**(1/n) print ('The Geometric Mean is: ' + str(geometric_mean))
Once you run the code in Python, you’ll get the same result: 16.9168
Method 3: Using Pandas and Scipy
You could also use Pandas and Scipy to obtain the geometric mean:
from pandas import DataFrame from scipy.stats.mstats import gmean data = {'values': [8,16,22,12,41]} df = DataFrame(data) geometric_mean = gmean(df.loc[:,'values']) print ('The Geometric Mean is: ' + str(geometric_mean))
As before, you’ll get the same geometric mean: 16.9168