Python Basics: Summarizing Measurements with statistics
A few summary numbers can make a small set of measurements easier to inspect. Python’s standard-library statistics module handles common averages and measures of spread.
Use Python 3.12 or newer in Bash on Linux. Each example runs independently with invented measurements in memory.
Compare the mean and median
Save as demo_statistics_1.py:
from statistics import mean, median
seconds = [2, 3, 3, 4, 18]
print("Mean:", mean(seconds))
print("Median:", median(seconds))
print("Even-sized median:", median([2, 3, 4, 18]))Run it from the directory where you saved it:
python3 demo_statistics_1.pyOutput:
Mean: 6
Median: 3
Even-sized median: 3.5The mean uses every value. The median is the middle of the sorted data, or the average of the two middle values. The slow measurement pulls the mean upward here. Neither number alone explains why it occurred.
Measure spread
Save as demo_statistics_2.py:
from statistics import pstdev, stdev
seconds = [2, 4, 4, 4, 5, 5, 7, 9]
print(f"Population standard deviation: {pstdev(seconds):.3f}")
print(f"Sample standard deviation: {stdev(seconds):.3f}")Run it from the directory where you saved it:
python3 demo_statistics_2.pyOutput:
Population standard deviation: 2.000
Sample standard deviation: 2.138Use pstdev() when these values are the entire population you intend to describe. Use stdev() to estimate spread from a sample of a larger population; it requires at least two values. Standard deviation has the same units as the input. The three decimal places are display rounding.
Handle missing and non-finite values explicitly
Save as demo_statistics_3.py:
from math import isfinite
from statistics import StatisticsError, mean
raw = [2.0, None, 4.0, float("nan"), float("inf")]
clean = [value for value in raw if value is not None and isfinite(value)]
print("Kept:", clean)
print("Dropped:", len(raw) - len(clean))
print("Mean:", mean(clean))
try:
mean([])
except StatisticsError:
print("No measurements to summarize")Run it from the directory where you saved it:
python3 demo_statistics_3.pyOutput:
Kept: [2.0, 4.0]
Dropped: 3
Mean: 3.0
No measurements to summarizeThis example deliberately drops missing and non-finite readings and reports the count. Decide whether to reject them instead for your data. The filter expects numbers or None; it does not parse strings. An empty result still needs handling. Validate inputs before calculating and keep the original measurements for investigation.
References
Acknowledgements
This post was created with assistance from AI.