17.6 C
London
Monday, July 21, 2025
HomePythonOperations in PythonHow to Calculate Geometric Mean in Python (With Examples)

How to Calculate Geometric Mean in Python (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories