In this shot, we will discuss how to use the statistics.harmonic_mean()
function in Python.
Statistics
is a very useful module in Python that provides functions to calculate mathematical statistics of numeric data.
Statistics
supports both int
and float
type numeric data. Some of the functions in the statistics
module in Python include:
mean()
median()
mode()
geometric_mean()
harmonic_mean()
To calculate the harmonic mean, we first find the sum of the reciprocals of all the observations, and then divide the total number of observations by that sum.
If a list of numbers contains a,b,c, then:
Harmonic mean =
For example, let the list of numbers be 1, 4, and 4. Their harmonic mean is:
= = 2
Let’s take a look at the code snippet below.
import statisticsdata = [1, 4, 4]result = statistics.harmonic_mean(data)print(result)
In line 1, we import the statistics
module to call harmonic_mean()
.
In line 2, we provide a list of data whose harmonic mean needs to be found.
In line 3, we compute the harmonic mean of the provided numbers.
In line 4, we print the output that is stored in the result.
Note:
Module_name.function_name
is the syntax for calling any function inside a module.
The statistics.harmonic_mean()
function comes in handy when we want to compute the central location of the dataset.