How to calculate geometric mean in Python (with examples)

How to Easily Calculate Geometric Mean in Python

The geometric mean is a specialized type of average that is essential when dealing with data sets where values are meant to be multiplied together or represent rates of change, unlike the standard arithmetic mean which uses addition. Calculating the geometric mean in Python involves finding the nth root of the product of all numbers in the series, where ‘n’ is the count of those numbers. This method is particularly vital in finance, biology, and data analysis when growth factors or proportions are central to the calculation.

Consider a simple series of three positive numbers: 2, 4, and 8. To manually calculate the geometric mean, one would first multiply them (2 * 4 * 8 = 64). Since there are three numbers (n=3), we take the cube root (or the 1/3 power) of the product: (64)**(1/3). The resulting value is 4, which is the geometric mean of this set. This powerful mathematical concept provides a robust measure of central tendency for exponentially scaled data, and the flexibility of Python allows us to implement this calculation efficiently across various data structures.


Understanding the Geometric Mean and Its Applications

The geometric mean (GM) is often confused with the arithmetic mean, but its application is fundamentally different. While the arithmetic mean answers “what is the average value if we added them up equally,” the GM answers “what is the average factor if we multiplied them consistently.” This makes it indispensable for applications involving compounding interest, population growth rates, or averaging different scales of data that exhibit multiplicative relationships. It ensures that extreme values have a less distorting impact compared to the arithmetic average, providing a more stable and representative measure of central tendency for skewed data distributions.

Mathematically, if you have a set of $k$ positive numbers, $x_1, x_2, …, x_k$, the formula for the geometric mean is given by: $text{GM} = sqrt[k]{x_1 x_2 cdots x_k}$. When programming this calculation in Python, handling the potential for extremely large products (overflow) or extremely small products (underflow) is crucial. This is why computational libraries often employ log-transformations, a technique we will explore when utilizing the NumPy package.

The Mathematical Foundation of Geometric Mean in Code

While the direct calculation (product raised to the power of $1/n$) is intuitive, data scientists often rely on an equivalent logarithmic transformation for computational stability, especially when dealing with large datasets or numbers spanning multiple orders of magnitude. The geometric mean can be calculated by taking the exponent of the arithmetic mean of the logarithms of the values. Specifically, $GM = e^{frac{1}{n} sum_{i=1}^{n} ln(x_i)}$. This approach leverages standard arithmetic functions on the transformed data, which is computationally safer and more efficient for modern machine learning and statistical computing tasks.

In Python, both the specialized statistical library SciPy and the fundamental numerical computing library NumPy provide robust tools to perform this calculation. The choice between the two often depends on the specific project context: SciPy offers a direct, pre-optimized function, while NumPy requires defining a custom function but relies solely on core numerical tools, offering deeper control over the implementation details. We will now detail both streamlined methods available to the modern Python user.

Calculating Geometric Mean in Python: Overview of Approaches

When working within the Python ecosystem, users have two primary, highly optimized ways to compute the geometric mean, leveraging powerful community-driven libraries. These methods deliver identical, validated results but differ significantly in implementation complexity and required dependencies. Understanding both techniques allows a developer to select the best tool for their environment, whether prioritizing simplicity or minimizing dependencies.

  • Method 1: Calculate Geometric Mean Using SciPy

    The SciPy library, specifically the scipy.stats module, provides a dedicated function called gmean(). This is the most straightforward and recommended approach for general statistical use, as the function handles underlying mathematical complexities and edge cases internally. It is ideal for quick calculations within statistical modeling pipelines.

  • Method 2: Calculate Geometric Mean Using NumPy

    This approach involves defining a custom function that utilizes core NumPy functions, such as log, mean, and exp, following the logarithmic transformation principle described earlier. While slightly more verbose, relying solely on NumPy can be advantageous in environments where SciPy might be an unnecessary or restricted dependency. This method showcases a deeper understanding of the numerical implementation.

Method 1: Utilizing the SciPy Library for Geometric Mean

The most concise and widely accepted methodology for statistical computations in Python involves using the gmean() function provided by the scipy.stats module. This module is built specifically for advanced statistics and probability theory, ensuring that its functions are rigorously tested and optimized for speed and numerical stability. To implement this, you only need to import the necessary function and pass your data series, typically presented as a NumPy array or a standard Python list, directly into the function call.

from scipy.stats import gmean

# Import the gmean function from the SciPy stats module
# This function accepts any iterable numerical series (e.g., list, NumPy array)
gmean([value1, value2, value3, ...])

This streamlined approach drastically reduces the chance of introducing programming errors that might arise from manual calculation loops or incorrect handling of indices. Furthermore, the gmean() function inherently manages the process of converting the input data into the optimal format for calculation, providing a high level of abstraction and ease of use for data analysts who prioritize rapid development and dependable results.

Method 2: Implementing Geometric Mean with NumPy Functions

For those preferring to avoid external statistical dependencies like SciPy, or for developers who require fine-grained control over the underlying mathematics, defining a custom function using NumPy is an excellent alternative. This method leverages the robust and highly performant logarithmic principle of geometric mean calculation ($GM = e^{text{mean}(ln(x))}$). By utilizing np.log(), np.mean(), and np.exp(), we can construct a function that is both mathematically sound and executed with C-optimized speed inherent to the NumPy library.

import numpy as np

#define custom function using the log-transform property
def g_mean(x):
    a = np.log(x)
    return np.exp(a.mean())

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

This implementation guarantees that both methods—the direct gmean() from SciPy and the custom logarithmic approach using NumPy—will yield results that are mathematically identical, differing only negligibly due to floating-point precision inherent in digital computation. The primary difference lies in the reliance on external libraries versus foundational components of the numerical Python stack.

Practical Demonstration: Comparing SciPy and NumPy Outputs

To solidify the understanding of these two methods, we will apply them to an identical dataset. This comparison highlights their ease of use and confirms their equivalence, which is crucial for validation in statistical modeling. We will use a representative array of eight positive integers: [1, 4, 7, 6, 6, 4, 8, 9]. The geometric mean, being the eighth root of the product ($1 times 4 times 7 times 6 times 6 times 4 times 8 times 9 = 241920$), should be approximately 4.8179.

Example 1: Calculate Geometric Mean Using SciPy

This code snippet demonstrates the straightforward application of the gmean() function. Note that while SciPy is highly efficient, it is important to remember that it is often built upon NumPy, meaning that using SciPy implicitly assumes NumPy is also installed and available in the environment. We pass the list directly, and the function returns the calculated value with high precision.

from scipy.stats import gmean

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

4.81788719702029

The resulting value, 4.8179 (when rounded to four decimal places), perfectly represents the central tendency of the multiplicative relationship within this data set. This confirms the efficacy and numerical accuracy of the specialized SciPy implementation for finding the geometric mean.

Example 2: Calculate Geometric Mean Using NumPy

The following example utilizes the custom function defined previously, showcasing how to achieve the identical result using only fundamental NumPy operations. This reinforces the logarithmic transformation principle and demonstrates how core numerical tools can replicate complex statistical measures. The input array remains identical, ensuring a true side-by-side comparison of the two methods.

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

As expected, the geometric mean calculated via the NumPy custom function also yields 4.8179 (when rounded). This confirms that, whether you choose the convenience of scipy.stats.gmean or the control provided by the logarithmic transformation using NumPy primitives, the calculated statistical measure remains consistent and accurate.

Addressing Data Integrity: Handling Zero Values

A crucial consideration when calculating the geometric mean is the presence of zero values in the dataset. Due to the fundamental definition of the geometric mean (which involves multiplying all elements), if any element in the input array is zero, the product of all elements will necessarily be zero. Consequently, the nth root of zero is zero, meaning both the SciPy and NumPy methods will return zero instantly if a zero is present. This is mathematically correct, but often not desirable if the zero represents a missing measurement or an irrelevant data point rather than a true factor of zero growth.

When implementing the logarithmic method using NumPy (Method 2), passing zero to the np.log() function results in an error (specifically, a RuntimeWarning for ‘divide by zero encountered in log’) and returns negative infinity, which further invalidates the final result. Therefore, before calculating the geometric mean, it is standard practice in data preparation to filter out or appropriately impute zero values if they are considered outliers or non-contributing data points rather than fundamental zeros in a growth factor series.

A common solution is to preemptively filter the input array to remove all non-positive values. The following Python code demonstrates how to use a list comprehension to efficiently create a new array containing only positive values before proceeding with the geometric mean calculation. This ensures the calculation remains meaningful and avoids numerical instability or misleading results.

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

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

#view updated array
print(x_new)

[1, 6, 6, 8, 9]

Considerations for Advanced Use: Negative Numbers and Edge Cases

While the geometric mean is fundamentally defined for positive real numbers, real-world data occasionally includes negative values. It is imperative to note that attempting to calculate the nth root of a negative product (which occurs if there is an odd number of negative factors) results in a complex number. Since the geometric mean typically requires a real-valued output, the presence of negative numbers usually renders the standard geometric mean inappropriate or requires complex domain calculation, which is beyond the scope of most general statistical analyses.

In most statistical packages, including SciPy and NumPy, passing negative values will lead to runtime warnings (e.g., “invalid value encountered in log” when using the logarithmic method) and often result in NaN (Not a Number) outputs, indicating that the calculation could not be performed meaningfully within the real number system. Therefore, best practice strongly advises ensuring that all data points are strictly positive (i > 0) before initiating the calculation of the geometric mean in Python.

Cite this article

stats writer (2025). How to Easily Calculate Geometric Mean in Python. PSYCHOLOGICAL SCALES. Retrieved from https://scales.arabpsychology.com/stats/how-to-calculate-geometric-mean-in-python-with-examples/

stats writer. "How to Easily Calculate Geometric Mean in Python." PSYCHOLOGICAL SCALES, 4 Dec. 2025, https://scales.arabpsychology.com/stats/how-to-calculate-geometric-mean-in-python-with-examples/.

stats writer. "How to Easily Calculate Geometric Mean in Python." PSYCHOLOGICAL SCALES, 2025. https://scales.arabpsychology.com/stats/how-to-calculate-geometric-mean-in-python-with-examples/.

stats writer (2025) 'How to Easily Calculate Geometric Mean in Python', PSYCHOLOGICAL SCALES. Available at: https://scales.arabpsychology.com/stats/how-to-calculate-geometric-mean-in-python-with-examples/.

[1] stats writer, "How to Easily Calculate Geometric Mean in Python," PSYCHOLOGICAL SCALES, vol. X, no. Y, ص Z-Z, December, 2025.

stats writer. How to Easily Calculate Geometric Mean in Python. PSYCHOLOGICAL SCALES. 2025;vol(issue):pages.

Download Post (.PDF)
Slide Up
x
PDF
Scroll to Top