The Wayback Machine - https://web.archive.org/web/20240525002953/https://www.geeksforgeeks.org/python-statistics-median/
Open In App

median() function in Python statistics module

Last Updated : 27 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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.
median() function in the statistics module can be used to calculate median value from an unsorted data-list. The biggest advantage of using median() function is that the data-list does not need to be sorted before being sent as parameter to the median() function.
Median is the value that separates the higher half of a data sample or probability distribution from the lower half. For a dataset, it may be thought of as the middle value. The median is the measure of the central tendency of the properties of a data-set in statistics and probability theory. Median has a very big advantage over Mean, which is the median value is not skewed so much by extremely large or small values. The median value is either contained in the data-set of values provided or it doesn’t sway too much from the data provided.
For odd set of elements, the median value is the middle one. 
For even set of elements, the median value is the mean of two middle elements.
 

Median can be represented by the following formula :

{\displaystyle \mathrm {median} (a)={\frac {a_{\lfloor \#x\div 2\rfloor }+a_{\lfloor \#x\div 2+0.5\rfloor }}{2}}}


  
 

Syntax : median( [data-set] )
Parameters : 
[data-set] : List or tuple or an iterable with a set of numeric values
Returns : Return the median (middle value) of the iterable containing the data
Exceptions : StatisticsError is raised when iterable passed is empty or when list is null. 
 


Code #1 : Working
 

Python3

# Python code to demonstrate the 
# working of median() function.
 
# importing statistics module
import statistics
 
# unsorted list of random integers
data1 = [2, -2, 3, 6, 9, 4, 5, -1]
 
 
# Printing median of the
# random data-set
print("Median of data-set is : % s "
        % (statistics.median(data1)))

                    

Output : 
 

Median of data-set is : 3.5 


  
Code #2 : 
 

Python3

# Python code to demonstrate the
# working of median() on various
# range of data-sets
 
# importing the statistics module
from statistics import median
 
# Importing fractions module as fr
from fractions import Fraction as fr
 
# tuple of positive integer numbers
data1 = (2, 3, 4, 5, 7, 9, 11)
 
# tuple of floating point values
data2 = (2.4, 5.1, 6.7, 8.9)
 
# tuple of fractional numbers
data3 = (fr(1, 2), fr(44, 12),
         fr(10, 3), fr(2, 3))
 
# tuple of a set of  negative integers
data4 = (-5, -1, -12, -19, -3)
 
# tuple of set of positive
# and negative integers
data5 = (-1, -2, -3, -4, 4, 3, 2, 1)
 
# Printing the median of above datasets
print("Median of data-set 1 is % s" % (median(data1)))
print("Median of data-set 2 is % s" % (median(data2)))
print("Median of data-set 3 is % s" % (median(data3)))
print("Median of data-set 4 is % s" % (median(data4)))
print("Median of data-set 5 is % s" % (median(data5)))

                    

Output : 
 

Median of data-set 1 is 5
Median of data-set 2 is 5.9
Median of data-set 3 is 2
Median of data-set 4 is -5
Median of data-set 5 is 0.0


  
Code #3 : Demonstrating StatisticsError 
 

Python3

# Python code to demonstrate
# StatisticsError of median()
 
# importing the statistics module
from statistics import median
 
# creating an empty data-set
empty = []
 
# will raise StatisticsError
print(median(empty))

                    

Output : 
 

Traceback (most recent call last):
  File "/home/3c98774036f97845ee9f65f6d3571e49.py", line 12, in 
    print(median(empty))
  File "/usr/lib/python3.5/statistics.py", line 353, in median
    raise StatisticsError("no median for empty data")
statistics.StatisticsError: no median for empty data


  
Applications : 
For practical applications, different measures of dispersion and population tendency are compared on the basis of how well the corresponding population values can be estimated. For example, a comparison shows that the sample mean is more statistically efficient than the sample median when the data is uncontaminated by data from heavily-tailed data distribution or from mixtures of data distribution, but less efficient otherwise and that the efficiency of the sample median is higher than that for a wide range of distributions. To be more specific, the median has 64% efficiency compared to minimum-variance-mean ( for large normal samples ).
 



Similar Reads

mode() function in Python statistics module
The mode of a set of data values is the value that appears most often. It is the value at which the data is most likely to be sampled. A mode of a continuous probability distribution is often considered to be any value x at which its probability density function has a local maximum value, so any peak is a mode.Python is very robust when it comes to
5 min read
median_low() function in Python statistics module
Median is often referred to as the robust measure of the central location and is less affected by the presence of outliers in data. statistics module in Python allows three options to deal with median / middle elements in a data set, which are median(), median_low() and median_high(). The low median is always a member of the data set. When the numb
4 min read
median_high() function in Python statistics module
Median is often referred to as the robust measure of the central location and is less affected by the presence of outliers in data. statistics module in Python allows three options to deal with median / middle elements in a data set, which are median(), median_low() and median_high(). The high median is always a member of the data set. When the num
4 min read
median_grouped() function in Python statistics module
Coming to Statistical functions, median of a data-set is the measure of robust central tendency, which is less affected by the presence of outliers in data. As seen previously, medians of an ungrouped data-set using median(), median_high(), median_low() functions. Python gives the option to calculate the median of grouped and continuous data functi
4 min read
stdev() method in Python statistics module
Statistics module in Python provides a function known as stdev() , which can be used to calculate the standard deviation. stdev() function only calculates standard deviation from a sample of data, rather than an entire population. To calculate standard deviation of an entire population, another function known as pstdev() is used. Standard Deviation
5 min read
Os Module Vs. Sys Module In Python
Python provides a lot of libraries to interact with the development environment. If you need help using the OS and Sys Module in Python, you have landed in the right place. This article covers a detailed explanation of the OS and Sys Module including their comparison. By the end of this article, you will be able to easily decide which module suits
5 min read
Python statistics | mean() function
Prerequisite : Introduction to Statistical FunctionsPython 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
4 min read
Python - Power-Function Distribution in Statistics
scipy.stats.powerlaw() is a power-function continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution. Parameters : q : lower and upper tail probability x : quantiles loc : [optional]location parameter. Default = 0
2 min read
fmean() function in Python statistics
Statistics module of Python 3.8 provides a function fmean() that converts all the data into float data-type and then computes the arithmetic mean or average of data that is provided in the form of a sequence or an iterable. The output of this function is always a float. The only difference in computing mean using mean() and fmean() is that while us
3 min read
Numpy MaskedArray.median() function | Python
numpy.MaskedArray.median() function is used to compute the median along the specified axis of a masked array.It returns the median of the array elements. Syntax : numpy.ma.median(arr, axis=None, out=None, overwrite_input=False, keepdims=False) Parameters: arr : [ ndarray ] Input masked array. axis :[ int, optional] Axis along which the median is co
3 min read
Practice Tags :