The Python statistics module has a number of useful functions, such as mean(), fmean(), geometric_mean() and harmonic_mean() function. Lets write some code snippets and understand how to use the mean function in Python statistics module.
Calculating mean value of given data
The mean value of a given set of data items is the average value of the data items. The mean can be calculated by adding all the numbers and dividing the obtained sum by the number of data items. There are 3 functions available for the same.
- mean() function
- fmean() function
- geometric_mean() function
- harmonic_mean() function
Using the mean() function
The mean() function calculates the mean value of a given list of numbers. The list of numbers need not be any sorted order, they can be arranged in a random order. The mean value is returned as a int value or a float value. The below code snippet explains the usage and syntax of mean() function.
# using the mean() function on a given list of numbers
import statistics
numbers1 = [10, 20]
mean1 = statistics.mean(numbers1)
print("The given numbers are ", numbers1)
print("The mean value is ", mean1) # returns 15
numbers2 = [10, 21]
mean2 = statistics.mean(numbers2)
print("The given numbers are ", numbers2)
print("The mean value is ", mean2) # returns 15.5
Using the fmean() function
The fmean() function is similar to the mean() function. The difference is that the function converts all the values to float and then computes the mean. Hence this function always returns a float value.
# using the fmean() function on a given list of numbers
import statistics
numbers1 = [10, 20]
mean1 = statistics.fmean(numbers1)
print("The given numbers are ", numbers1)
print("The mean value is ", mean1) # returns 15.0
numbers2 = [10, 21]
mean2 = statistics.fmean(numbers2)
print("The given numbers are ", numbers2)
print("The mean value is ", mean2) # returns 15.5
Using the geometric_mean() function
The geometric_mean() function calculates the mean in a different way. The geometric mean is calculated by multiplying all the numbers and then finding the nth root of the obtained product.
#using the geometric_mean() function
import statistics
numbers = [9, 15, 25]
mean = statistics.geometric_mean(numbers)
print("The given numbers are ", numbers)
print("The geometric mean value is ", mean) # returns 15.0