Mean, Median, Mode
Compute central tendency metrics to summarize data distributions before modeling.
Why Measures of Central Tendency Matter
Understanding the middle of your data helps you detect skew, outliers, and potential preprocessing steps. Mean, median, and mode guide feature engineering and model expectations.
Using NumPy and Pandas
import numpy as np
import pandas as pd
data = np.array([12, 15, 14, 10, 18, 12])
mean = data.mean()
median = np.median(data)
mode = pd.Series(data).mode().iloc[0]
print(mean, median, mode)Pandas returns a Series for mode(); access the first value to retrieve the most frequent element.
Weighted Mean
Apply weights when values contribute unequally to the overall measure.
weights = np.array([0.1, 0.2, 0.2, 0.1, 0.4, 0.0])
weighted_mean = np.average(data, weights=weights)Detecting Skew and Outliers
Compare mean and median to identify skew. Large differences suggest heavy tails or outliers. Complement with box plots and violin plots (see Matplotlib lessons).
Best Practices
- Handle missing values before calculating statistics.
- Use median for skewed distributions or when outliers exist.
- Document calculation methods and data sources (share updates via
info.studygrid@gmail.com).
Next Steps
Continue to the standard deviation tutorial to quantify variability around the mean.
Try It Yourself
Exercise 1: Find the mean, median, and mode of [4, 8, 8, 15, 16, 23, 42].
Show solution
import statistics as st
data = [4, 8, 8, 15, 16, 23, 42]
print(st.mean(data), st.median(data), st.mode(data))
# 16.57... 15 8Exercise 2: Why might the median be a better "typical" value than the mean for incomes?
Show solution
Incomes are right-skewed: a few very high earners pull the mean upward, so it overstates the typical income. The median is unaffected by those outliers.
Key Takeaways
- Mean is the average, median the middle, mode the most frequent.
- Use the median for skewed data or when outliers exist.
- Comparing mean and median reveals skew.
📘 Real-World Deep Dive
Knowing <strong>ML Mean Median Mode (scikit-learn)</strong> well is what turns scikit-learn from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of ML Mean Median Mode that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
import statistics as st
samples = [2, 3, 3, 4, 5, 7, 9]
print("mean:", st.mean(samples))
print("median:", st.median(samples))
print("mode:", st.mode(samples))Expected Output
(see source)Common mistakes
fitexpects numeric arrays;OneHotEncoder/LabelEncoderare easy to forget for categorical features.- Calling
predicton a model trained on unscaled data and then scaling inputs at inference time silently degrades accuracy. train_test_split(X, y)requires both arrays;train_test_split(X)for unsupervised learning slips past static checkers.- Treating ML Mean Median Mode as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- Wrap preprocessing + estimator in a
Pipelinesofit/predictstay reproducible. - Use
joblib/picklefor serialising models, not the entire Python state. - For > 100 k rows, switch to
HistGradientBoostingClassifierorcuML. - When working with scikit-learn, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.