Python statistics

mean/median/mode, variance, quantiles, and when to reach for NumPy instead.

Beginner
Key Points`statistics` is pure Python and exact with Decimal/Fraction; switch to NumPy when you need speed or arrays.

Central Tendency

The mean is dragged by outliers, the median is not. For latency (a long-tail distribution) P95/P99 beats the mean.

Python
import statistics as st

data = [12, 15, 15, 18, 22, 150]
print(st.mean(data))
print(st.median(data))
print(st.mode(data))
Output
38.666666666666664
16.5
15

Dispersion

stdev is the sample standard deviation (n-1); pstdev is the population one (n). Use the sample version when your data is a subset.

Python
import statistics as st

data = [12, 15, 15, 18, 22]
print(round(st.stdev(data), 3))
print(round(st.pstdev(data), 3))
print(round(st.variance(data), 3))
Output
4.183
3.741
17.5

Quantiles

quantiles(data, n=100) returns percentile cut points — index into it for P95/P99, the standard SLA report.

Python
import statistics as st

latency = [10, 12, 13, 15, 18, 21, 25, 40, 90, 300]
qs = st.quantiles(latency, n=100)
print("P50", qs[49], "P95", qs[94], "P99", qs[98])
Output
P50 21 P95 258.0 P99 294.0
Above tens of thousands of points, statistics gets slow — switch to np.percentile, an order of magnitude faster.

Friends & Partners