Python Statistics Module
In this page:
Central Tendency
The built-in statistics module offers simple, dependency-free functions for common calculations: statistics.mean() computes the arithmetic average and statistics.median() finds the middle value of a sorted dataset, which is more robust to outliers than the mean.
Example: Central Tendency
import statistics
data = [1, 2, 3, 4, 100]
print(statistics.mean(data))
print(statistics.median(data))
Mode and Frequency
statistics.mode() returns the single most frequently occurring value in a dataset, while statistics.multimode() returns all values tied for the most frequent when there's more than one. Mode is the only measure of central tendency that also makes sense for non-numeric, categorical data.
Example: Mode and Frequency
import statistics
data = [1, 2, 2, 3]
print(statistics.mode(data))
print(statistics.multimode([1, 1, 2, 2, 3]))
Dispersion Measures
statistics.variance() and statistics.stdev() quantify how spread out a dataset's values are around the mean -- a small standard deviation means values cluster tightly, a large one means they're widely scattered. Both come in population and sample variants (pvariance/pstdev vs variance/stdev), and picking the wrong one skews results for small datasets.
Example: Dispersion Measures
import statistics
data = [2, 4, 4, 4, 5, 5, 7, 9]
print(statistics.variance(data))
print(statistics.stdev(data))
Data Distribution Ranges
statistics.median_low() and statistics.median_high() resolve the ambiguity that arises when a dataset has an even number of values and there's no single middle element -- they return the lower and upper of the two central values respectively, instead of averaging them.
Example: Data Distribution Ranges
import statistics
data = [1, 2, 3, 4]
print(statistics.median_low(data))
print(statistics.median_high(data))
Harmonic and Geometric Means
statistics.geometric_mean() and statistics.harmonic_mean() are specialized averages suited to specific situations: geometric mean is appropriate for averaging rates of growth or ratios, and harmonic mean is appropriate for averaging rates like speed, where the arithmetic mean would give a misleading answer.
Example: Harmonic and Geometric Means
import statistics
data = [2, 8]
print(statistics.geometric_mean(data))
print(statistics.harmonic_mean(data))
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first:
- Python NumPy Introduction
- Python NumPy Arrays
- Python Pandas Introduction
- Python Pandas DataFrame
- Python Matplotlib Basics
- Python Data Visualization
- Python Statistics Module
- Python CSV & Data Analysis
- Python requests Module
- Python JSON & APIs
- Python Web Scraping Basics
- Python Flask Introduction
- Python Django Introduction
- Python MongoDB