Skip to main content
Describing Data - Mean and Central Tendency

Describing Data: What’s Normal?

The House Hunting Problem

You’re moving to Austin, Texas. You have a budget of $500,000 and want to know: Is that enough for a decent 3-bedroom house? You could look at one listing, but that’s just one data point. You need to understand the whole picture. Let’s load some real data:
Output:
The range is 389Kto389K to 1250K. But that doesn’t tell us what’s “typical”. We need better tools.

Measures of Central Tendency: “What’s Typical?”

The Mean (Average)

The mean is what most people think of as “average” - add everything up and divide by the count. Analogy: Think of the mean as the balance point of a seesaw. If you placed each data point as a weight along a beam, the mean is where you would put the fulcrum to make it balance perfectly. One very heavy weight far from center (an outlier) can shift the balance point dramatically.
Mean Formula Visualization
The mathematical formula: xˉ=1ni=1nxi=x1+x2+...+xnn\bar{x} = \frac{1}{n} \sum_{i=1}^{n} x_i = \frac{x_1 + x_2 + ... + x_n}{n}
Output:
Wait… 492.6K?Mosthousesarearound492.6K? Most houses are around 450K, but the mean is higher. What’s happening?
Mean Real World - Mansion Pulling Average
The Problem with the Mean: That $1.25M mansion is pulling the average up! The mean is sensitive to outliers.

The Median (Middle Value)

The median is the middle value when you sort the data. Half the values are above, half below.
Output:
The median is $472K - much more representative of a “typical” house! The mansion doesn’t affect it because it’s just one value above the middle.
When to use Mean vs Median?

The Mode (Most Common Value)

The mode is the value that appears most frequently. Less useful for continuous data, but great for categories.
Real-World Usage:
  • Most popular shirt size at a store
  • Most common customer complaint
  • Peak traffic hour

Measures of Spread: “How Different Are Things?”

Knowing the center isn’t enough. Consider these two neighborhoods:
Output:
Almost the same mean! But look at the actual houses:
  • Neighborhood A: All houses are between 445K445K-462K (consistent)
  • Neighborhood B: Houses range from 350Kto350K to 550K (huge variation)
We need to measure spread.

Range (Simplest Measure)

Output:
The range shows the difference, but it only uses two values and is sensitive to outliers.

Variance: Average Squared Distance from Mean

Variance measures how far values typically are from the mean.
Variance Formula Visualization
The Formula: σ2=1ni=1n(xixˉ)2\sigma^2 = \frac{1}{n} \sum_{i=1}^{n} (x_i - \bar{x})^2 Step by step:
  1. Find the mean
  2. For each value, calculate distance from mean
  3. Square each distance (makes all positive, penalizes big deviations)
  4. Average the squared distances
Output:
Neighborhood B has 171x more variance than A!
Variance Real World - Neighborhood Comparison

Standard Deviation: Variance in Original Units

Variance is in “squared dollars” which is hard to interpret. Standard deviation brings us back to dollars. σ=σ2=1ni=1n(xixˉ)2\sigma = \sqrt{\sigma^2} = \sqrt{\frac{1}{n} \sum_{i=1}^{n} (x_i - \bar{x})^2}
Output:
Interpretation:
  • Neighborhood A: Houses are typically within plus or minus $5.4K of the mean
  • Neighborhood B: Houses are typically within plus or minus $71K of the mean
Analogy: Standard deviation is like the “typical commute distance” of data points from their home (the mean). In Neighborhood A, every data point lives close to the mean — a short commute. In Neighborhood B, data points are scattered far and wide.
ML Application — Feature Scaling: Standard deviation is the foundation of standardization (z-score normalization), one of the most critical preprocessing steps in ML. When you run StandardScaler() in scikit-learn, it is dividing each feature by its standard deviation so all features have comparable scales. Skip this step with algorithms like gradient descent or SVM, and the features with larger scales will dominate learning — a classic beginner mistake that produces mysteriously poor models.
Sample vs Population: When working with a sample (not the entire population), we divide by (n-1) instead of n for variance. This is called Bessel’s correction.

Percentiles and Quartiles: “Where Does This Value Rank?”

Going back to our Austin house prices - is $500K expensive or affordable? Percentiles tell you what percentage of values fall below a given number.
Output:
Your $500K budget puts you at the 78th percentile - you can afford 78% of houses in this area!

The Interquartile Range (IQR)

The IQR is the range of the middle 50% of data: IQR=Q3Q1=P75P25IQR = Q3 - Q1 = P_{75} - P_{25}
Output:
That $1.25M mansion is definitely an outlier!

Visualizing Data: See the Distribution

Numbers are great, but our brains understand pictures better.

Box Plot (Box-and-Whisker)

Histogram


Complete Summary Statistics

Here’s a function that gives you the full picture:
Output:

🎯 Practice Exercises

Exercise 1: Salary Analysis

Exercise 2: Test Score Comparison


🏠 Mini-Project: House Price Analyzer

Build a complete house price analysis tool!
Output:

Key Takeaways

Central Tendency

  • Mean: Add and divide. Sensitive to outliers.
  • Median: Middle value. Robust to outliers.
  • Mode: Most common. Great for categories.

Spread

  • Range: Max - Min. Simple but limited.
  • Variance: Average squared distance from mean.
  • Std Dev: Square root of variance. Same units as data.

Position

  • Percentiles: What % of values fall below this?
  • Quartiles: 25th, 50th, 75th percentiles.
  • IQR: Range of middle 50%. Good for outlier detection.

When to Use What

  • Symmetric data: Mean + Std Dev
  • Skewed data: Median + IQR
  • Outliers present: Always check both!

Common Mistakes to Avoid

Mistake 1: Always Using the MeanThe mean can be heavily influenced by outliers. For salary data, housing prices, or any skewed distribution, the median is often more representative.Example: In a company where 9 employees earn 50KandtheCEOearns50K and the CEO earns 5M, the mean salary is $545K - wildly misleading!
Mistake 2: Ignoring UnitsVariance is in squared units, which can be hard to interpret. Standard deviation is in the original units, making it much more practical.Example: A variance of 10,000 dollars² is hard to understand. A std dev of $100 is clear.
Mistake 3: Comparing Std Devs Across Different ScalesA std dev of 10Kforhousepricesvs10K for house prices vs 10 for groceries aren’t comparable. Use the coefficient of variation (CV = std/mean) to compare relative variability.

Interview Questions

Question: You’re analyzing user session lengths. The mean is 45 minutes, but the median is only 8 minutes. What does this tell you about the distribution?
Answer: This indicates a heavily right-skewed distribution with outliers. Most users have short sessions (around 8 minutes), but some power users have very long sessions that pull the mean way up. The median is more representative of the “typical” user experience.
Question: You have a dataset of daily ad revenue. How would you identify outliers?
Answer: Use the IQR method:
  1. Calculate Q1 (25th percentile) and Q3 (75th percentile)
  2. Calculate IQR = Q3 - Q1
  3. Outliers are values below Q1 - 1.5×IQR or above Q3 + 1.5×IQR
Alternatively, use z-scores: values more than 3 standard deviations from the mean are typically considered outliers.
Question: You’re comparing two delivery drivers. Driver A has mean delivery time of 30 min (std dev 2 min). Driver B has mean 32 min (std dev 8 min). Which driver would you prefer?
Answer: Despite Driver A being slightly faster on average, the low variance is the key differentiator. Driver A is consistently fast (28-32 min range), while Driver B is unpredictable (could be 24-40 min). For customer satisfaction and logistics planning, consistency often matters more than a slightly faster mean.
Question: We measure page load times. The mean is 2.5 seconds, but the 99th percentile is 15 seconds. What action might you take?
Answer: The 99th percentile (P99) being 6x the mean suggests there’s a “long tail” of slow experiences. Even though 99% of users have decent load times, 1% are having a terrible experience. For a company with millions of users, that’s a lot of frustrated customers. Focus on identifying what causes these edge cases - geographic regions, specific devices, or server issues.

Practice Challenge

You’re given website session data. Analyze it completely:
Solution:

📝 Practice Exercises

Exercise 1

Calculate descriptive statistics for employee salaries

Exercise 2

Analyze website load times for performance optimization

Exercise 3

Detect outliers in e-commerce transaction data

Exercise 4

Real-world: Analyze housing market price distributions

How This Connects to Machine Learning

Everything you just learned is foundational to ML:
Statistical Mistake in ML — Using Mean on Skewed Targets: If your target variable (the thing you are predicting) is right-skewed — like house prices, income, or time-to-event data — training a regression model on the raw values causes the model to overweight expensive outliers. The fix: check skewness first. If mean and median diverge significantly, apply a log transform to the target before training. This single step routinely improves RMSE by 10-30% on real datasets.

Interview Prep: Common Questions

Q: When would you use median instead of mean?
Use median when data has outliers or is heavily skewed. Classic examples: income data (billionaires skew the mean), house prices, response times (occasional timeouts).
Q: How do you detect outliers?
Common methods: IQR method (1.5 × IQR beyond Q1/Q3), z-score method (beyond ±2 or ±3 standard deviations), visual inspection with box plots.
Q: What’s the difference between population and sample variance?
Population variance divides by n, sample variance divides by (n-1). Use n-1 for samples because it provides an unbiased estimate of population variance (Bessel’s correction).
Q: A dataset has mean = median. What does this tell you?
The distribution is likely symmetric (not skewed). In a perfectly symmetric distribution, mean = median = mode.

Common Pitfalls

Mistakes to Avoid:
  1. Using mean for skewed data - Always check for outliers first; median is often more representative
  2. Ignoring the spread - Two datasets can have identical means but completely different distributions
  3. Confusing variance units - Variance is in squared units; use standard deviation for interpretable scale
  4. Forgetting to visualize - Statistics alone can be misleading (Anscombe’s quartet is the classic example)

Key Takeaways

What You Learned:
  • Mean - Sum divided by count; sensitive to outliers
  • Median - Middle value; robust to outliers; use for skewed data
  • Mode - Most frequent value; useful for categorical data
  • Variance & Std Dev - Measure spread around the mean
  • Percentiles & IQR - Divide data into portions; detect outliers
  • Z-scores - Standardize values across different scales
Coming up next: We’ll learn about probability - how to quantify uncertainty and make predictions. This is where statistics becomes truly powerful!

Next: Probability Foundations

Learn to quantify uncertainty and make predictions

Interview Deep-Dive

Strong Answer:
  • The large gap between mean (85K)andmedian(85K) and median (42K) tells me the distribution is heavily right-skewed. A small number of very high-revenue days — likely driven by flash sales, holiday events, or a few massive B2B orders — are pulling the mean upward. On a “typical” day, the company makes closer to $42K.
  • I would report both numbers to the VP, but frame it carefully: “On a normal day, we generate about 42Kinrevenue.However,ouraverageishigherat42K in revenue. However, our average is higher at 85K because we have occasional spike days that significantly boost the total. If you are planning staffing and operations around daily expectations, use the median. If you are forecasting monthly totals, the mean times 30 gives a better estimate.”
  • I would also present the P90 and P99 to show how extreme the spike days are, and potentially a histogram showing the bimodal or long-tail shape. Stakeholders make better decisions when they understand the shape, not just a single number.
  • The key risk: if someone uses the $85K mean for daily budgeting, they will overspend on most days and then scramble during the rare high days. Conversely, if they use only the median, they will underestimate total monthly revenue.
Follow-up: How would you detect whether the spike days are periodic (like weekends or holidays) versus random?I would decompose the time series by day of week and month to check for seasonal patterns. A simple groupby on day-of-week showing that Saturday revenue is 3x the weekday median would confirm a weekly cycle. For holiday effects, I would flag known retail events (Black Friday, Prime Day) and compare flagged versus unflagged days. If the spikes are periodic, you can model them with seasonal adjustments. If they are random (driven by viral social media posts or unpredictable B2B orders), then you need a different forecasting approach that accounts for heavy-tailed distributions — perhaps a log-normal model rather than a normal one.
Strong Answer:
  • Standard deviation assumes your data is roughly symmetric and does not have extreme outliers. It uses every data point including the tails, so a single extreme value can inflate it dramatically. It is the right choice when your data is approximately normal — test scores, manufacturing measurements, or sensor readings from a calibrated instrument.
  • IQR (the range between the 25th and 75th percentiles) is robust to outliers because it only looks at the middle 50% of the data. It is the right choice for skewed or contaminated data — income distributions, transaction amounts, page load times, or any dataset where you suspect data quality issues at the extremes.
  • In practice, the choice has real consequences. If you use standard deviation for fraud detection thresholds on transaction amounts (which are heavily right-skewed), the outliers inflate the std dev so much that your “anomaly threshold” becomes absurdly high and you miss actual fraud. Using IQR-based thresholds (like the 1.5 x IQR rule) gives much more practical detection boundaries.
  • A concrete example: at a payments company, transaction amounts might have mean 50,stddev50, std dev 500 (because of a few 10Kwiretransfers).A"meanplus3sigma"thresholdwouldbe10K wire transfers). A "mean plus 3 sigma" threshold would be 1,550, which misses all the moderately fraudulent 200200-300 transactions. An IQR-based approach with Q3 around 80wouldflaganythingaboveroughly80 would flag anything above roughly 125 as worth investigating.
Follow-up: You mentioned the 1.5 x IQR rule. Where does that 1.5 come from, and when would you adjust it?The 1.5 multiplier was introduced by John Tukey for box plots and corresponds roughly to the boundaries that would capture about 99.3% of a normal distribution. For normal data, Q1 minus 1.5 x IQR and Q3 plus 1.5 x IQR align approximately with mean plus or minus 2.7 standard deviations. You would adjust the multiplier based on your tolerance for false positives: use 3.0 x IQR for “extreme outliers” when you want very high confidence, or drop to 1.0 if you want a more aggressive filter. In fraud detection, you often tune this multiplier empirically against labeled fraud data to optimize the precision-recall tradeoff for your specific domain.
Strong Answer:
  • Anscombe’s quartet is a set of four datasets that have nearly identical summary statistics — same mean of x, same mean of y, same variance, same correlation coefficient (r approximately 0.816), and the same regression line — yet look completely different when plotted. One is a normal linear relationship, one is a perfect curve, one is a perfect line with one outlier, and one has all points at one x-value except for a single extreme point.
  • The lesson is devastating for anyone who relies on summary statistics alone: the numbers can lie. Two datasets with identical means, variances, and correlations can have fundamentally different structures, and any model or decision built on those numbers without visual inspection could be wildly wrong.
  • In practice, this means every analysis should start with visualization. Before computing a single correlation or fitting a regression, plot a scatterplot, a histogram, or a residual plot. At companies with large data pipelines, I have seen teams ship models based on correlation matrices without ever looking at the actual data shape — and later discover non-linear relationships, clustering, or data artifacts that invalidated their approach.
  • The modern extension is the Datasaurus Dozen, which shows the same idea with 13 datasets (including one shaped like a dinosaur) that all share the same summary statistics. It reinforces that summary stats are a lossy compression of your data — useful for communication, but dangerous as the sole basis for decisions.
Follow-up: In a large-scale ML pipeline where you cannot manually visualize every feature pair, how do you catch these kinds of issues?You build automated data profiling into the pipeline. Tools like pandas-profiling, Great Expectations, or custom checks can flag non-linearity (by comparing Pearson versus Spearman correlations — if they diverge, the relationship is non-linear), detect bimodality (using the dip test or kernel density estimation), and identify influential outliers (using Cook’s distance). You also set up distribution dashboards that sample and plot key feature pairs on a rotating basis. The goal is not to inspect every combination manually but to have automated red flags that trigger human review when something looks off.