In my earlier articles, we have see calculating mean, median and mode in SQL Server and C#.NET. Unlike SQL Server and .NET, Python programming language has an inbuilt module called statistics which has some basic mathematical statistics functions including mean, median and mode. This statistics module was introduced in Python version 3.4.
The statistics module has multiple functions. Below are the functions which calculate mean, median and mode.
- mean() : To get the arithmetic mean of the given set of data. Arithmetic mean is also the average of the data.
- median() : To get the median or the middle value of the given set of data.
- mode() : To get the single mode of the given set of data. If there are multiple modes in the data, then this function returns the first mode it identifies.
- multimode() : Lists all the modes in the given set of data. If there is no mode, then this function will return all the elements of the data.
Here is the sample code to find mean, median and mode in Python using the statistics module.
import statistics data = [220, 100, 190, 180, 250, 190, 240, 180, 140, 180, 190] # Finding Mean print("\nMean: ", statistics.mean(data)) # Finding Median print("Median: ", statistics.median(data)) # Finding Single Mode print("Single Mode: ", statistics.mode(data)) # Finding Multiple Modes print("Mode: ", statistics.multimode(data))
Mean: 187.27272727272728 Median: 190 Single Mode: 190 Mode: [190, 180]
- Read more about Python’s statistics module at Python Docs.