Harmonic Mean in Python (2 Examples)

 

This tutorial explains how to calculate the harmonic mean in Python.

The article consists of two examples for the computation of the harmonic mean. To be more precise, the page looks as follows:

Let’s get started!

 

Exemplifying Data

Consider the following example data:

my_list = [4, 3, 8, 7, 8, 4, 4, 1, 5]       # Create example list
print(my_list)                              # Print example list
# [4, 3, 8, 7, 8, 4, 4, 1, 5]

The previously shown output of the Python console shows the structure of our example data: We have created a list object containing nine list elements.

 

Example 1: Get Harmonic Mean Using harmonic_mean() Function of statistics Module

In Example 1, I’ll illustrate how to use the harmonic_mean function of the statistics module to calculate the harmonic mean in Python.

We need to import the statistics module, in order to use the commands and functions that are contained in the module:

import statistics                           # Import statistics

Next, we can use the harmonic_mean function to get the harmonic mean of our data:

print(statistics.harmonic_mean(my_list))    # Apply statistics.harmonic_mean function
# 3.3629893238434163

As you can see, the harmonic mean of our example list is 3.36.

 

Example 2: Get Harmonic Mean Using hmean() Function of SciPy Library

Alternatively to the statistics module, we can also use the SciPy library to calculate the harmonic mean.

As a first step, we have to import the hmean function of the SciPy library:

from scipy.stats import hmean               # Import SciPy

Next, we can apply this function to calculate the harmonic mean of our list:

print(hmean(my_list))                       # Apply hmean function
# 3.362989323843416

As you can see, the output is basically the same as in Example 1.

 

Video, Further Resources & Summary

Have a look at the following video on the Statistics Globe YouTube channel. I’m showing the Python programming syntax of this tutorial in the video:

 

The YouTube video will be added soon.

 

In addition, you could have a look at some of the related articles on this website:

 

To summarize: In this article you have learned how to get the harmonic mean in Python. In case you have additional questions, let me know in the comments section.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top