How to Calculate Secondary Metrics in Python
Computes distribution, variability, and spread of a numeric dataset using Python's statistics and collections modules.
Python code
39 linesimport random
import statistics
from collections import Counter
def explore_secondary_metrics(data):
"""Calculate secondary metrics: distribution, variability, and spread."""
if not data:
return "No data provided"
total = sum(data)
mean = statistics.mean(data)
median = statistics.median(data)
mode = statistics.mode(data)
variance = statistics.variance(data) if len(data) > 1 else 0
stdev = statistics.stdev(data) if len(data) > 1 else 0
distribution = Counter(data)
return {
"count": len(data),
"sum": total,
"mean": round(mean, 2),
"median": median,
"mode": mode,
"variance": round(variance, 2),
"standard_deviation": round(stdev, 2),
"distribution": dict(distribution)
}
if __name__ == "__main__":
random.seed(42)
sample_data = [random.randint(1, 10) for _ in range(12)]
metrics = explore_secondary_metrics(sample_data)
print("Sample Data:", sample_data)
print("\nSecondary Metrics:")
for key, value in metrics.items():
print(f"{key.replace('_', ' ').title()}: {value}")
Output
Sample Data: [7, 1, 1, 9, 6, 10, 6, 4, 8, 1, 10, 2]
Secondary Metrics:
Count: 12
Sum: 65
Mean: 5.42
Median: 6.0
Mode: 1
Variance: 11.72
Standard Deviation: 3.42
Distribution: {7: 1, 1: 3, 9: 1, 6: 2, 10: 2, 4: 1, 8: 1, 2: 1}
How it works
The function first validates input to avoid division-by-zero and empty-set errors. It then wraps statistics functions — mean, median, mode, variance, and stdev — which are designed to handle realistic numeric lists. The Counter object provides a frequency distribution that captures how often each value appears, which is essential for understanding data shape beyond averages. Variance and standard deviation quantify spread, with variance in squared units and stdev in the same units as the data. Rounding to two decimals keeps output concise without losing practical precision.
Common mistakes
- Calling `statistics.mode` on an empty list raises `StatisticsError`
- Forgetting to guard `variance` and `stdev` for single-element lists which raise `StatisticsError`
- Passing non-numeric data which causes `TypeError` in statistics functions
Variations
- Use `pandas.DataFrame.describe()` for a broader set of metrics on a DataFrame
- Implement custom percentile calculations with `statistics.quantiles`
Real-world use cases
- Exploratory data analysis during A/B test analysis to check balance of secondary metrics between groups.
- Monitoring dashboard generation that plots daily distribution and spread of user engagement scores.
- Feature engineering in ML pipelines with variance and standard deviation as derived features.
Sponsored
More from A/B testing & experimentation
Keep learning
Related tutorials and quizzes for this topic.