This is a quick tutorial to find Mean, Median, and Mode in Python. We’ll calculate Mean & Median using numpy module & Mode using the spicy module.
Calculating Mean, Median & Mode in Python
Mean, Median & Mode are a great way to measure the central value of a data series. If you want to learn more about these values, check out the following article by purplemath.com
We’ll directly begin with our tutorial i.e how you can calculate these values in python. As mentioned earlier, we’ll be using the numpy module for calculating the Mean & Median and spicy module for calculating the mode. You can quickly install these modules on your computer using the pip command. Just run the following commands.
pip install numpy
pip install spicy
Once, you installed it, you can calculate any of the values from mean, median and mode for any set of numerical data values in just a single line of code. The module
median objects and the module spicy provide the object
stats.mode. You just have to pass a list of numerical values as an argument to these objects and the mean, median and mode values will automatically be calculated for you.
Let’s understand this with the help of an example. I’ve taken a list of a few random numbers. Then using numpy, I am calculating the mean, median and mode.
from scipy import stats
#Storing the Data as Python List
data = [10,11,9,32,45,92,22,34,45,21,15,18,88,24,50]
mean = numpy.mean(data)
median = numpy.median(data)
mode = stats.mode(data)
print("Mode: "+str(mode.mode) + ", Number of Time Appearing: " + str(mode.count))
stats.mode() provides another object that contains the mode and also the count for the mode value i.e. how many times the mode number is appearing in the data list. Therefore, we’ve used
mode.count to find the actual mode value and count.
So, this way you can easily calculate Mean, Median and Mode in Python using the numpy and spicy modules. I hope you found this guide useful. If so, do share it with others who are willing to learn Python. If you have any questions related to this article, feel free to ask us in the comments section.
And do not forget to subscribe to WTMatter!