Descriptive Statistics with the statistics Module
The standard `statistics` module provides high-accuracy statistical math without third-party libraries: `mean()`, `median()`, `mode()`, `stdev()`, and `quantiles()` 📊.
import statistics
response_times = [12, 15, 18, 22, 22, 25, 45, 98]
print(f"Mean: {statistics.mean(response_times):.1f}ms 📊")
print(f"Median: {statistics.median(response_times):.1f}ms 🎯")
print(f"Mode: {statistics.mode(response_times)}ms 📈")
print(f"Std Dev: {statistics.stdev(response_times):.1f}ms 📉")
# 49. Descriptive Statistics with the statistics Module The standard `statistics` module provides high-accuracy statistical math without third-party libraries: `mean()`, `median()`, `mode()`, `stdev()`, and `quantiles()` 📊. ```python import statistics response_times = [12, 15, 18, 22, 22, 25, 45, 98] print(f"Mean: {statistics.mean(response_times):.1f}ms 📊") print(f"Median: {statistics.median(response_times):.1f}ms 🎯") print(f"Mode: {statistics.mode(response_times)}ms 📈") print(f"Std Dev: {statistics.stdev(response_times):.1f}ms 📉") ``` The `statistics` module also supports `statistics.quantiles(data, n=100)` to calculate P95 and P99 latency percentiles for real-time observability pipelines! 📊 --- ### Question Why is `median()` preferred over `mean()` when reporting server latency metrics with extreme outlier spikes? 🧠- [ ] a. The median is robust against extreme outliers, whereas a few 10-second spikes severely distort the arithmetic mean 🎯 - [ ] b. The mean is only calculated on integers - [ ] c. Median runs in $O(1)$ time while mean runs in $O(n^2)$ - [ ] d. Mean is deprecated in modern data engineering --- ### Challenge Import `statistics`. Given `latencies = [100, 102, 105, 5000]`, calculate `statistics.median(latencies)`. Print the median. 🎯 <details> <summary>Solution</summary> ```python import statistics latencies = [100, 102, 105, 5000] med = statistics.median(latencies) print(med) ``` </details>