How to calculate geometric mean in Python (with examples)

Geometric mean in Python can be calculated by taking the nth root of the product of the numbers in the series. For example, to calculate the geometric mean of 2, 4, and 8, the calculation would be (2*4*8)**(1/3). This would be 4, which is the geometric mean of these three numbers. This same formula can be used to calculate the geometric mean of any set of numbers in Python.


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 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 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.

#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]

x