Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python statistics.median() Function



The Python statistics.median() function calculates the median of the given data set. This function also sorts the given data in ascending order before calculating the median. The mathematical formula for the median is −

Median = {(n + 1)/2}

Where. n is the number of values in a set of data. The median is the number in the middle.

If the number of data values is odd, then it returns the exact middle value. If the number of data values is even, it returns the average of the two middle numbers.

Syntax

Following is the basic syntax of the statistics.median() function −

statistics.median(data)

Parameter

Here, the data values can be used as any sequence, list or iterator.

Return Value

This function returns the median of the given data.

Example 1

In the below example, we are finding the median for the odd numbers using statistics.median() function.

import statistics
x = statistics.median([1, 3, 5, 7, 9, 11, 13, 15, 17])
print(x)

Output

The output obtained is as follows −

9

Example 2

Here, we are calculating the median for even numbers using statistics.median() function.

import statistics
x = statistics.median([1, 7, 4, 2, 4, 6, 8, 1])
print(x)

Output

We will get the following output as −

4.0

Example 3

Now we are calculating the median for the negative numbers using statistics.median() function.

import statistics
print(statistics.median([-11, -5.5, -3.4, -7.1, -9, -22]))

Output

The result is produced as follows −

-8.05
python_modules.htm
Advertisements