How to calculate harmonic mean in Python?

The harmonic mean is a type of average, often used in situations where you want to find the average rate or ratio. Let’s see how to calculate harmonic mean in Python.

harmonic mean

To calculate the harmonic mean, we need to import the statistics module.

Using the statistics Module

Fortunately, the statistics module provides a dedicated function for calculating the harmonic mean.

import statistics as s

x = [1, 5, 7, 8, 43, 6]
harmonic_mean = s.harmonic_mean(x)
print(f"Harmonic mean equals: {round(harmonic_mean, 2)}")

This function automatically handles the calculation, making it a convenient option.

See also  How to calculate quartiles in Python?

Using scipy.stats.hmean

For those working in scientific computing, the scipy library offers an alternative:

from scipy.stats import hmean

x = [1, 5, 7, 8, 43, 6]
harmonic_mean = hmean(x)
print(f"Harmonic mean equals: {round(harmonic_mean, 2)}")

Manual Calculation

Alternatively, you can perform the harmonic mean calculation manually to gain insight into how it works:

x = [1, 5, 7, 8, 43, 6]
harmonic_mean = len(x) / sum(1 / item for item in x)
print(f"Harmonic mean equals: {round(harmonic_mean, 2)}")