Home » How to Calculate Geometric Mean in Python (With Examples)

How to Calculate Geometric Mean in Python (With Examples)

by Tutor Aspire

There are two ways to calculate the geometric mean in Python:

Method 1: Calculate Geometric Mean Using SciPy

from scipy.stats import gmean

#calculate geometric mean
gmean([value1, value2, value3, ...])

Method 2: Calculate Geometric Mean Using NumPy

import numpy as np

#define custom function
def g_mean(x):
    a = np.log(x)
    return np.exp(a.mean())

#calculate geometric mean 
g_mean([value1, value2, value3, ...])

Both methods will return the exact same results.

The following examples show how to use each of these methods in practice.

Example 1: Calculate Geometric Mean Using SciPy

The following code shows how to use the gmean() function from the SciPy library to calculate the geometric mean of an array of values:

from scipy.stats import gmean

#calculate geometric mean
gmean([1, 4, 7, 6, 6, 4, 8, 9])

4.81788719702029

The geometric mean turns out to be 4.8179.

Example 2: Calculate Geometric Mean Using NumPy

The following code shows how to write a custom function to calculate a geometric mean using built-in functions from the NumPy library:

import numpy as np

#define custom function
def g_mean(x):
    a = np.log(x)
    return np.exp(a.mean())

#calculate geometric mean
g_mean([1, 4, 7, 6, 6, 4, 8, 9])

4.81788719702029

The geometric mean turns out to be 4.8179, which matches the result from the previous example.

How to Handle Zeros

Note that both methods will return a zero if there are any zeros in the array that you’re working with.

Thus, you can use the following bit of code to remove any zeros from an array before calculating the geometric mean:

#create array with some zeros
x = [1, 0, 0, 6, 6, 0, 8, 9]

#remove zeros from array 
x_new = [i for i in x if i != 0]

#view updated array
print(x_new)

[1, 6, 6, 8, 9]

Additional Resources

How to Calculate Mean Squared Error (MSE) in Python
How to Calculate Mean Absolute Error in Python

You may also like