Let’s see how to calculate the geometric mean in 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)))

## Calculating a geometric mean using numpy

You can use the Numpy Python library. To calculate the numpy geometric mean, you need to use such a code:

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

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.