Python statistics
mean/median/mode, variance, quantiles, and when to reach for NumPy instead.
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
15Dispersion
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.5Quantiles
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.0Above tens of thousands of points,
statistics gets slow — switch to np.percentile, an order of magnitude faster.集中趋势
均值会被极端值拉偏,中位数不会。接口耗时这类长尾分布,看 P95/P99 比看均值有意义得多。
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离散程度
stdev 是样本标准差(除以 n-1),pstdev 是总体标准差(除以 n)。数据只是总体的一部分时用前者。
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(data, n=100) 直接给出百分位切点,配合索引就能算 P95、P99 —— 这是 SLA 报表的标准做法。
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数据量超过几万条或需要矩阵运算时,
statistics 会明显变慢 —— 换 NumPy 的 np.percentile,性能差一个量级。