How to Use the Python statistics.median() Function

How to Use the Python statistics.median() Function

Introduction

Among the various statistical measures, the median is a key metric providing insight into the central tendency of a dataset. Unlike the mean, which can be heavily influenced by outliers, the median offers a more robust representation of the data’s center, especially in skewed distributions.

Let’s take a look at using the Python statistics.median() function, a valuable tool for calculating the median of a dataset.

Using the statistics.median() Function

Before you can utilize any function from the statistics module, you must first import it into your Python environment.

import statistics

The statistics.median() function is designed to compute the median of a given dataset. The function syntax is as follows:

statistics.median(data)

Here, the parameter data is expected to be a list (or any iterable) of numerical values.

Let’s start with a straightforward example using a list of integers.

data = [1, 3, 3, 6, 7, 8, 9]
median_value = statistics.median(data)
print(f"The median is: {median_value}")

# Output: The median is: 6

In this case, the median is 6, as it is the middle value when the list is sorted. When the list has an odd number of elements, the median is simply the middle element.

Now consider a list with an even number of elements.

data_even = [1, 2, 3, 4, 5, 6]
median_value_even = statistics.median(data_even)
print(f"The median is: {median_value_even}")

# Output: The median is: 3.5

Here, the output will be 3.5, which is the average of the two middle numbers (3 and 4) in the sorted list.

The statistics.median() function can also handle lists of float values.

data_float = [1.5, 2.7, 3.3, 4.1]
median_value_float = statistics.median(data_float)
print(f"The median is: {median_value_float}")

# Output: The median is: 3.0

For this dataset, the median is 3.0, which is the mean of the 2 middle float values when the numbers are sorted.

Calculating the median of an empty list will raise an error. Here’s an example:

data_empty = []
try:
    median_value_empty = statistics.median(data_empty)
except ValueError as e:
    print(f"Error: {e}")

# Output: Error: no median for empty data

The output will indicate that a ValueError occurred because there are no data points to calculate the median.

If the list contains non-numeric values, a TypeError will be raised.

data_invalid = [1, 2, 'three', 4]
try:
    median_value_invalid = statistics.median(data_invalid)
except TypeError as e:
    print(f"Error: {e}")

# Output: Error: '<' not supported between instances of 'str' and 'int'

It’s important to keep in mind that the statistics.median() function is not optimized for speed as compared to methods offered by libraries such as NumPy. If you are working with very large arrays or require high performance for statistical calculations, consider using NumPy, which is designed for efficiency.

In NumPy, you can use the numpy.median() function:

import numpy as np

# Generate a large dataset
large_data = np.random.rand(1000000)
median_value_numpy = np.median(large_data)
print(f"The median using NumPy is: {median_value_numpy}")

Wrapping Up

The Python statistics.median() function is a straightforward tool for calculating the median, whether you’re dealing with integers or floats. For further information, check out the Python statistics module documentation, as well as the documentation forother libraries like NumPy and Pandas.

Leave a Reply

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