Python’s statistics module is a simple yet powerful tool for performing common statistical operations. This module comes built-in with Python and provides functions for calculating mean, median, mode, standard deviation, variance, and more.
Whether you’re handling data analysis tasks, performing descriptive statistics, or trying to extract insights from datasets, the statistics module can be a go-to solution.
The statistics module offers functions to compute mathematical statistics of numeric data. It is best suited for small datasets, and for larger datasets, libraries such as NumPy or pandas might be preferable.
Here, we’ll explore the following key statistical functions with detailed examples:
mean(): Arithmetic mean.median(): Middle value of the dataset.mode(): Most frequent value.stdev(): Standard deviation.variance(): Measure of how data is spread.harmonic_mean(): Mean for rates/ratios.median_low()andmedian_high(): Low and high median values.
1. Calculating the Mean
The mean is the average of the data. It’s the most common measure of central tendency.
import statistics
# Dataset for calculation
data = [15, 25, 35, 45, 55]
# Calculate the mean
mean_value = statistics.mean(data)
print("Mean:", mean_value)
Output:
Mean 35
In this case, the mean is calculated as (15 + 25 + 35 + 45 + 55) / 5 = 35.
Example with Floats:
data_floats = [1.5, 2.5, 3.5, 4.5]
mean_floats = statistics.mean(data_floats)
print("Mean (Floats):", mean_floats)
Output:
Mean (Floats): 3.0
Even with decimal numbers, the mean is calculated accurately.
2. Calculating the Median
The median is the value separating the higher half from the lower half of the data. If the number of elements is even, the median is the average of the two middle numbers.
# Example dataset
data_odd = [1, 3, 5, 7, 9]
# Calculate the median for an odd number of elements
median_value = statistics.median(data_odd)
print("Median (Odd elements):", median_value)
Output:
Median (Odd elements): 5
If the dataset contains an even number of elements:
data_even = [10, 20, 30, 40]
median_value_even = statistics.median(data_even)
print("Median (Even elements):", median_value_even)
output:
Median (Even elements): 25.0
For even datasets, the median is the average of the middle two numbers (20 + 30) / 2 = 25.
3. Calculating the Mode
The mode is the most frequent value in the dataset. If multiple values appear with the same frequency, statistics.mode() raises a StatisticsError.
# Dataset with a mode
data_mode = [1, 2, 2, 3, 4]
# Calculate the mode
mode_value = statistics.mode(data_mode)
print("Mode:", mode_value)
Output:
Mode: 2
Example with Multiple Modes:
# Example dataset with multiple modes
data_multimode = [1, 1, 2, 2, 3]
# Mode calculation
try:
mode_multimode = statistics.mode(data_multimode)
print("Mode:", mode_multimode)
except statistics.StatisticsError as e:
print("Error:", e)
In this case, statistics.mode() will raise an error because there are two modes (1 and 2).
4. Calculating the Standard Deviation
The standard deviation measures how spread out the numbers in a dataset are relative to the mean. A higher standard deviation means the values are more spread out.
# Calculate the standard deviation
stdev_value = statistics.stdev(data)
print("Standard Deviation:", stdev_value)
Output:
Standard Deviation: 15.811388300841896
The standard deviation tells us that the data points are, on average, 15.81 units away from the mean.
5. Calculating the Variance
Variance measures the spread of numbers. It’s the average of the squared differences from the mean.
# Calculate the variance
variance_value = statistics.variance(data)
print("Variance:", variance_value)
Output:
Variance: 250
Variance is the square of the standard deviation (stdev^2), and it gives us an idea of how much the data is dispersed from the mean.
6. Calculating the Harmonic Mean
The harmonic mean is often used when dealing with averages of rates or ratios.
# Example dataset for harmonic mean
data_harmonic = [2, 3, 4]
# Calculate harmonic mean
harmonic_mean_value = statistics.harmonic_mean(data_harmonic)
print("Harmonic Mean:", harmonic_mean_value)
Output:
Harmonic Mean: 2.769230769230769
7. Low and High Median
When a dataset has an even number of elements, you can find the lower and upper median using median_low() and median_high() respectively.
# Dataset with even number of elements
data_even_median = [10, 20, 30, 40]
# Low and high median
low_median = statistics.median_low(data_even_median)
high_median = statistics.median_high(data_even_median)
print("Low Median:", low_median)
print("High Median:", high_median)
Output:
Low Median: 20
High Median: 30
8. Working with Empty and Single-Element Lists
The statistics module handles edge cases such as empty lists or lists with a single element gracefully. Let’s see how it reacts to these scenarios.
# Single-element list
single_element = [42]
# Mean of a single-element list
mean_single = statistics.mean(single_element)
print("Mean (Single element):", mean_single)
Output:
Mean (Single element): 42
For an empty list:
# Empty list case
empty_data = []
try:
mean_empty = statistics.mean(empty_data)
except statistics.StatisticsError as e:
print("Error:", e)
This will raise a StatisticsError because it is not possible to compute the mean of an empty dataset.
9. Working with Floating-Point Numbers
You can also use the statistics module for floating-point datasets, where precision matters.
# Floating-point dataset
float_data = [2.5, 3.6, 4.1, 5.8]
# Calculate mean, median, and standard deviation
mean_float = statistics.mean(float_data)
median_float = statistics.median(float_data)
stdev_float = statistics.stdev(float_data)
print(f"Mean (Float): {mean_float}")
print(f"Median (Float): {median_float}")
print(f"Standard Deviation (Float): {stdev_float}")
Output:
Mean (Float): 4.0
Median (Float): 3.85
Standard Deviation (Float): 1.3722590473761982
Conclusion
The statistics module in Python is a versatile and user-friendly tool for basic statistical analysis. From computing measures of central tendency like the mean, median, and mode to understanding data spread with variance and standard deviation, the module provides essential functions for small-scale data analysis. While larger datasets might require more advanced libraries like NumPy or pandas, the statistics module is sufficient for everyday tasks.
This module is perfect for beginners as well as professionals needing to perform quick, reliable statistical calculations. Its wide range of functions and ability to handle edge cases make it a valuable tool in Python’s standard library. Whether you’re working with integers, floating-point numbers, or real-world datasets, the statistics module equips you with the basic statistical tools you need for meaningful data analysis.





Leave a Reply