How to calculate geometric mean in Python?

Let’s see how to calculate the geometric mean in Python. The geometric mean is a measure of central tendency that is useful for dealing with data that has a wide range of values and is often used in finance, biology, and other fields.

geometric mean python

Calculating a geometric mean with the statistics module

To calculate the geometric average, we need to import the statistics module.

Luckily, there is a dedicated function in the statistics module to calculate the geometric mean.

import statistics as s

x = [1, 5, 7, 8, 43, 6]

geometric_mean = s.geometric_mean(x)
print("Geometric mean equals: " + str(round(geometric_mean, 2)))

The statistics.geometric_mean function computes the geometric mean of the values in the list x. In this example, the geometric mean is rounded to two decimal places:

See also  How to solve ValueError: setting an array element with a sequence

Calculating a geometric mean using numpy

For calculating the geometric mean using the NumPy library, follow this approach:

import statistics as s
import numpy as np

x = [1, 5, 7, 8, 43, 6]

geometric_mean = np.exp(np.mean(np.log(x)))
print("Geometric mean equals: " + str(round(geometric_mean, 2)))

In this approach, we first compute the natural logarithm of the data points, calculate their mean, and then exponentiate the result to obtain the geometric mean.

See also  Correcting AxisError: axis x is out of bounds for array of dimension y

The output is as follows:

Geometric mean equals: 6.45

Calculating a geometric mean using scipy

Alternatively, you can use scipy to calculate a geometric mean.

from scipy.stats import gmean

x = [1, 5, 7, 8, 43, 6]

geometric_mean = gmean(x)
print("Geometric mean equals: " + str(round(geometric_mean, 2)))

As you can see, gmean is the function that you can use to calculate the scipy geometric mean.

See also  How to Calculate the Determinant of a Matrix in Numpy

By using these methods and libraries, you can efficiently calculate the geometric mean in Python, making it a valuable tool for various statistical and data analysis tasks.