Statistics in python – mean, mode and median

In this article, we shall see how to perform some of the statistical functions such as mean, median, and mode. This can be done with the help of a python module called statistics. This module offers many more methods and functionalities than these three alone. The only three topics that will be discussed here are,

  1. mean
  2. median
  3. mode

Let us look at the modules one by one with an example for each.

Mean

The mean method from the statistics module takes an iterator and returns the arithmetic mean of the iterators. This will not work with a list of strings and only with numbers.

from statistics import mean

li = [2, 2, 2, 4, 2]
print(mean(li))

The output of the above code is,

2.4

Median

The statistics module also has a method called the median. The median is the middle number in a sorted, ascending or descending, list of numbers and can be more descriptive of that data set than the average.

This will work both with a list of numbers ans strings.

from statistics import median

li = [2, 2, 3, 4, 2]
print(median(li))

li = ['a', 'b', 'c', 'd', 'e']
print(median(li))

Mode

The next method is called the mode. The mode is the number that appears most frequently in a data set. A set of numbers may have one mode, more than one mode, or no mode at all. 

The mode will also work with a list of numbers or with a list of strings.

from statistics import mode

li = [2, 2, 3, 4, 2]
print(mode(li))

li = ['a', 'a', 'c', 'd', 'e']
print(mode(li))

The output of the above code is,

2
a

If there are multiple values with the same frequency it will throw us an exception called StatisticsError.

from statistics import mode

li = ['a', 'b', 'c', 'd', 'e']
print(mode(li))

In this example we have all the elements of the list with a frequency of 1. If we execute this code we will get an exception like this,

Traceback (most recent call last):
  File "/Users/PycharmProjects/pythonsnippets/mode_example.py", line 4, in <module>
    print(mode(li))
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/statistics.py", line 506, in mode
    'no unique mode; found %d equally common values' % len(table)
statistics.StatisticsError: no unique mode; found 5 equally common values

As you can see the system says that there is “no unique mode; found 5 equally common values“.

other usage: We can also use this method to find the most frequent element in a list.

Conclusion

Hope this article is helpful. Follow us regularly for more interesting ideas and topics. If you have any queries leave them below in the comments.

Happy coding!.