Python – Calculate Mean, Median & Mode

This is a quick tutorial to finding Mean, Median, and Mode in Python. We’ll calculate the Mean & Median using the NumPy module & Mode using the spicy module.

Calculating Mean, Median & Mode in Python

Mean, Median & Mode are great ways 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 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 numpy provides mean & 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.

Example

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.

import numpy
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
mean = numpy.mean(data)
print("Mean: "+str(mean))
#Median
median = numpy.median(data)
print("Median: "+str(median))
#Mode
mode = stats.mode(data)
print("Mode: "+str(mode.mode[0]) + ", Number of Time Appearing: " + str(mode.count[0]))

Python Mean, Median And Mode Calculation Example

The 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.mode[0] and mode.count[0] 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.

Leave a Reply

Your email address will not be published. Required fields are marked *