Prerequisite : Introduction to Statistical Functions
Python is a very popular language when it comes to data analysis and statistics. Luckily, Python3 provide statistics module, which comes with very useful functions like mean(), median(), mode() etc.
mean() function can be used to calculate mean/average of a given list of numbers. It returns mean of the data set passed as parameters.
Arithmetic mean is the sum of data divided by the number of data-points. It is a measure of the central location of data in a set of values which vary in range. In Python, we usually do this by dividing the sum of given numbers with the count of number present.
Given set of numbers : [n1, n2, n3, n5, n6]
Sum of data-set = (n1 + n2 + n3 + n4 + n5)
Number of data produced = 5
Average or arithmetic mean = (n1 + n2 + n3 + n4 + n5) / 5
Syntax : mean([data-set])
Parameters :
[data-set] : List or tuple of a set of numbers.
Returns : Sample arithmetic mean of the provided data-set.
Exceptions :
TypeError when anything other than numeric values are passed as parameter.
Code #1 : Working
Python3
import statistics
data1 = [ 1 , 3 , 4 , 5 , 7 , 9 , 2 ]
x = statistics.mean(data1)
print ( "Mean is :" , x)
|
Output :
Mean is : 4.428571428571429
Code #2 : Working
Python3
from statistics import mean
from fractions import Fraction as fr
data1 = ( 11 , 3 , 4 , 5 , 7 , 9 , 2 )
data2 = ( - 1 , - 2 , - 4 , - 7 , - 12 , - 19 )
data3 = ( - 1 , - 13 , - 6 , 4 , 5 , 19 , 9 )
data4 = (fr( 1 , 2 ), fr( 44 , 12 ), fr( 10 , 3 ), fr( 2 , 3 ))
data5 = { 1 : "one" , 2 : "two" , 3 : "three" }
print ( "Mean of data set 1 is % s" % (mean(data1)))
print ( "Mean of data set 2 is % s" % (mean(data2)))
print ( "Mean of data set 3 is % s" % (mean(data3)))
print ( "Mean of data set 4 is % s" % (mean(data4)))
print ( "Mean of data set 5 is % s" % (mean(data5)))
|
Output :
Mean of data set 1 is 5.857142857142857
Mean of data set 2 is -7.5
Mean of data set 3 is 2.4285714285714284
Mean of data set 4 is 49/24
Mean of data set 5 is 2
Code #3 : TypeError
Python3
from statistics import mean
dic = { "one" : 1 , "three" : 3 , "seven" : 7 ,
"twenty" : 20 , "nine" : 9 , "six" : 6 }
print (mean(dic))
|
Output :
Traceback (most recent call last):
File "/home/9f8a941703745a24ddce5b5f6f211e6f.py", line 29, in
print(mean(dic))
File "/usr/lib/python3.5/statistics.py", line 331, in mean
T, total, count = _sum(data)
File "/usr/lib/python3.5/statistics.py", line 161, in _sum
for n, d in map(_exact_ratio, values):
File "/usr/lib/python3.5/statistics.py", line 247, in _exact_ratio
raise TypeError(msg.format(type(x).__name__))
TypeError: can't convert type 'str' to numerator/denominator
Applications :
Mean/Arithmetic average is one of the very important function, while working with statistics and large values. So, with the function like mean(), trending and featured values can be extracted from the large data sets.