On this page
  1. statistics
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Percentiles / Quartiles (quantiles) & Linear Regression
  7. 2. Normal Distributions & Z-Scores (NormalDist)
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

statistics

Prev: stat | Up: stdlib_module | Next: string
Rel: numbers, math, cmath, decimal, fractions
Ref: docs.python.org — statistics
Tags: #public #python3 #stdlib


Import

import statistics

Overview

Zero-dependency descriptive statistics (mean, fmean, median, mode, stdev, pstdev, variance, quantiles, correlation, linear_regression, NormalDist) for small-to-medium numeric datasets. Reach for statistics when you want clean summary metrics without pulling in NumPy/SciPy.

Quick Start

import statistics

latencies_ms = [12.4, 15.1, 14.8, 13.0, 42.0]
assert round(statistics.fmean(latencies_ms), 2) == 19.46
assert statistics.median(latencies_ms) == 14.8
assert round(statistics.stdev(latencies_ms), 2) == 12.64

Implementation Walkthrough

1. Percentiles / Quartiles (quantiles) & Linear Regression

import statistics

samples = [10, 12, 14, 15, 18, 22, 25, 30, 45, 90]
q1, med, q3 = statistics.quantiles(samples, n=4)
assert q1 < med < q3

xs = [1.0, 2.0, 3.0, 4.0]
ys = [2.1, 3.9, 6.2, 7.9]
fit = statistics.linear_regression(xs, ys)
assert 1.8 < fit.slope < 2.2

2. Normal Distributions & Z-Scores (NormalDist)

from statistics import NormalDist

dist = NormalDist(mu=100, sigma=15)
assert round(dist.zscore(130), 2) == 2.0
assert 0.97 < dist.cdf(130) < 0.98

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes