When Not All Data Points Deserve Equal Say
Descriptive Statistics
The Weighted Mean: Giving Voice to What Matters
A four-credit course should not count the same as a one-credit elective. The weighted mean fixes the blind spots of simple averages.
- GPA calculation — credit hours determine how much each grade matters
- Portfolio returns — dollar weights reveal true investment performance
- Survey correction — adjusting for who actually responded versus who should have
What You'll Learn
- 1Derive the weighted mean as a rescaled arithmetic mean and state the invariance to weight normalization
- 2Compute credit-weighted GPA and money-weighted portfolio returns by hand and with NumPy
- 3Rebuild a mean from grouped frequency data using class midpoints as values and frequencies as weights
- 4Choose between weighted means, weighted medians, and inverse-variance pools for skewed or noisy data
The arithmetic mean treats every observation as equally deserving of influence, and that assumption fails constantly. A one-credit elective sits beside a four-credit capstone in an unweighted average, collapsing the transcript's real signal. A thousand-dollar position rides equally with a hundred-thousand-dollar position in a portfolio's "average return," inventing a performance number no investor experienced. The weighted mean repairs the damage by attaching an influence weight to each observation and averaging with those weights — the same idea that runs beneath survey post-stratification, price indices, ensemble models, and the attention mechanism of every transformer.
The Formula and What Weights Really Mean
The formula divides by the total weight rather than by , which buys two useful properties at once. First, the weights need not sum to one: credits, dollar amounts, population counts, and survey hits all work as raw weights, because the denominator normalizes them automatically. Second, normalizing the weights to sum to one changes nothing — scale every weight by the same constant and both numerator and denominator scale together. What matters is the ratio : that fraction, often called the normalized weight, is each observation's true share of the average. Equal weights recover the arithmetic mean exactly, which positions the simple average as a special case rather than a rival.
| Situation | Natural weight | Why the simple mean misleads |
|---|---|---|
| Semester GPA | Credit hours | A 1-credit elective would outweigh a 4-credit capstone |
| Portfolio return | Dollars invested | Equal-weight average ignores position sizes |
| Survey estimates | Population share per stratum | Over-represented groups skew the headline |
| Grouped frequency data | Class frequencies | Midpoints represent different numbers of rows |
| Instrument fusion | Inverse variance | Noisy sensors would dominate a plain average |
A Semester of Grades, Computed by Hand
Five courses close out a term: Statistics (4 credits, grade 4.0), Linear Algebra (3 credits, 3.7), Machine Learning (4 credits, 3.3), Databases (3 credits, 4.0), and Ethics (1 credit, 3.0). The credit-weighted sum is against 15 total credits, so the GPA lands at . The unweighted average of the five grade points is a flat 3.6. The 0.087 gap runs in the student's favor because the 4.0s arrived in high-credit courses — and if Ethics had carried four credits instead of one, the weighted GPA would fall below the unweighted figure. Transcript readers compute weighted means for exactly this reason: the weights encode how much of the student's time each grade represents.
import numpy as np
import pandas as pd
courses = pd.DataFrame({
'Course': ['Statistics', 'Linear Algebra', 'Machine Learning', 'Databases', 'Ethics'],
'Grade_Points': [4.0, 3.7, 3.3, 4.0, 3.0],
'Credits': [4, 3, 4, 3, 1],
})
weighted_gpa = np.average(courses['Grade_Points'], weights=courses['Credits'])
simple_gpa = courses['Grade_Points'].mean()
print(courses.to_string(index=False))
print(f"\nCredit total: {courses['Credits'].sum()}")
print(f"Weighted GPA: {weighted_gpa:.4f} (hand check: 55.3 / 15)")
print(f"Unweighted GPA: {simple_gpa:.4f}")
print(f"Difference: {weighted_gpa - simple_gpa:+.4f}")
Portfolio Returns: Money Is the Weight
A portfolio holds 40 percent in Stock A returning 12.5 percent, 35 percent in Stock B returning −3.2 percent, 20 percent in Bonds returning 4.1 percent, and 5 percent in Cash returning 0.5 percent. The money-weighted return is percent. The equal-weight average of the four returns is 3.475 percent, a full percentage point away from what the account statement shows. The divergence has a direction: money concentrates in the best performer, so the weighted figure exceeds the naive one. Run the experiment with the worst performer heavily weighted and the sign flips. Performance reports that average sleeve returns without dollar weights are describing a portfolio that does not exist, which is why custodians always publish asset-weighted figures and why rebalancing schedules — which deliberately shift weights — are documented alongside the return series.
portfolio = pd.DataFrame({
'Asset': ['Stock A', 'Stock B', 'Bonds', 'Cash'],
'Weight_pct': [40, 35, 20, 5],
'Return_pct': [12.5, -3.2, 4.1, 0.5],
})
portfolio_return = np.average(portfolio['Return_pct'], weights=portfolio['Weight_pct'])
simple_avg = portfolio['Return_pct'].mean()
print(portfolio.to_string(index=False))
print(f"\nDollar-weighted return: {portfolio_return:.3f}% (hand check: 4.725)")
print(f"Equal-weight average: {simple_avg:.3f}%")
print(f"Gap: {portfolio_return - simple_avg:+.3f} percentage points")
Grouped Frequency Data and Midpoint Weights
Binned data hides individual values, but not the mean. Take frequencies 5, 8, 12, and 5 over the classes 0–10, 10–20, 20–30, and 30–40. Each class is represented by its midpoint — 5, 15, 25, 35 — and the frequency is that midpoint's weight. The weighted sum over 30 observations gives a mean of 20.67. This estimator is approximate: it assumes values inside each bin are symmetric around the midpoint, so heavy skew inside the widest class introduces bias that shrinks only as bins narrow. Despite that caveat, the midpoint-weighted mean is the standard reconstruction used in histograms, census tables, and any pipeline that discards raw values for storage but must still report central tendency.
bins = pd.DataFrame({
'Class': ['0-10', '10-20', '20-30', '30-40'],
'Midpoint': [5, 15, 25, 35],
'Frequency': [5, 8, 12, 5],
})
grouped_mean = np.average(bins['Midpoint'], weights=bins['Frequency'])
total_n = bins['Frequency'].sum()
weighted_sum = (bins['Midpoint'] * bins['Frequency']).sum()
print(bins.to_string(index=False))
print(f"\nSum of f*m = {weighted_sum}, n = {total_n}")
print(f"Grouped mean = {weighted_sum / total_n:.4f} (hand check: 20.6667)")
Properties That Catch Bugs Before They Ship
Four invariants turn into cheap unit tests. Equal weights reproduce the arithmetic mean. The result always lies between the smallest and largest observation, no matter how extreme the weights — a weighted mean of values in cannot escape that interval, so an out-of-range output means the code is broken, not the data. Concentrating nearly all weight on one observation drags the mean toward that value, which is how post-stratification silently re-centers a survey on whichever stratum received the largest population share. And a ten percent error in one weight moves the mean by roughly ten percent of that observation's distance from the current average — small for clustered data, painful when the weighted observation is an outlier. Checking these behaviors on the first batch of a pipeline catches unit mismatches — weights in percentages versus fractions — before they contaminate a quarter of reporting.
data = np.array([10, 20, 30, 40, 50])
print(f"Equal weights: {np.average(data, weights=[1, 1, 1, 1, 1]):.2f} (matches mean {data.mean():.2f})")
extreme = np.average(data, weights=[1, 1, 1, 1, 100])
print(f"Weight 100 on 50: {extreme:.2f} (pulled toward 50, still inside [10, 50])")
w = np.array([4, 3, 4, 3, 1], dtype=float)
normed = w / w.sum()
print(f"\nRaw weights {w.astype(int)} vs normalized {normed.round(3)}")
print(f"Same mean either way: {np.average(data, weights=w):.4f} == "
f"{np.average(data, weights=normed):.4f}")
Weighted Mean, Weighted Median, and Weighted Variance
Weighting extends past the mean, and choosing the right weighted summary matters when data skew. The weighted median is the smallest value whose cumulative normalized weight reaches 0.5; it is the correct pooled center for income, cost, and latency data where a few large values hijack any mean. Weighted variance accumulates and divides by the total weight (or a degrees-of-freedom correction for unbiased survey estimates). Inverse-variance weighting is the statistical application with the sharpest edge: two instruments measuring the same length report 10.2 with standard deviation 1.0 and 9.6 with standard deviation 3.0. Precision weights are , so 1 and 1/9, and the pooled estimate is — pulled hard toward the precise instrument, exactly as Gauss showed optimal in 1823. Meta-analysis, sensor fusion, and fixed-effects regression all run on this pool.
| Summary | Weighted form | Robust to outliers | Typical use |
|---|---|---|---|
| Mean | No | GPA, portfolio return, indices | |
| Median | Cumulative weight crosses 0.5 | Yes | Income, latency, cost |
| Variance | No | Precision and risk models | |
| Mode | Largest weight mass at one value | Yes | Category popularity |
Machine learning reuses the machinery at scale. Stacking ensembles weight base models by out-of-fold accuracy; loss functions apply per-sample weights so rare classes are not drowned; exponential moving averages assign geometrically decaying weights to recent batches; and the attention mechanism is literally a weighted mean of value vectors, with weights produced by softmax over query-key scores. Recognizing attention as a weighted mean demystifies the transformer: the architecture's core operation is the same formula a registrar applies to a transcript, differentiated only by where the weights come from.
readings = np.array([10.2, 9.6])
sigmas = np.array([1.0, 3.0])
precision = 1.0 / sigmas ** 2
pooled = np.average(readings, weights=precision)
plain = readings.mean()
print(f"Precision weights: {precision.round(4)}")
print(f"Inverse-variance pool: {pooled:.4f} (hand check: 10.14)")
print(f"Plain average: {plain:.4f}")
# Softmax attention as a weighted mean of token embeddings
tokens = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])
attn = np.array([0.7, 0.2, 0.1])
context = np.average(tokens, axis=0, weights=attn)
print(f"\nAttention weights {attn} over three token vectors")
print(f"Context vector: {context.round(3)} (70% of token 1, 20% of token 2, 10% of token 3)")
Common Mistakes
Dividing a weighted sum by n instead of by the total weight
Fix: The denominator must be the sum of the weights; dividing by n silently shrinks the result whenever weights do not sum to one.
Mixing weight units within one average
Fix: Credits, dollars, and population counts cannot share a formula; normalize each weight source to a common scale before combining.
Reporting a weighted mean for heavily skewed data
Fix: Check the distribution first; for income or latency, a weighted median communicates the typical observation far better.
Best Practices
- Store weights and values together in one table so totals and means cannot drift apart
- Assert that the weighted mean falls inside the data range on every batch
- Normalize weights once at ingestion, then treat them as fractions of a whole
- Publish the weighting scheme next to any headline average for auditability
Key Takeaways
- The weighted mean divides by the total weight, so raw credits, dollars, and counts all work without pre-normalization
- Equal weights reduce it to the arithmetic mean; concentrating weight pulls it toward that observation
- GPA, portfolio returns, price indices, and grouped-data means are all weighted means in disguise
- Inverse-variance weighting pools noisy measurements optimally, and attention is a learned weighted mean of embeddings
Frequently Asked Questions
Do weights have to sum to one?
No. The formula divides by the sum of the weights, so any positive scale works — credits, dollars, headcounts. Normalizing to one is a convenience for interpretation, not a requirement, and the resulting mean is identical either way.
How is a weighted mean different from simply repeating observations?
They coincide when weights are integers: weighting a value by 3 equals including it three times in the dataset. Fractional weights have no repetition interpretation, which is why the formula — not the expanded dataset — is the right implementation for survey and precision weights.
When should I use a weighted median instead?
When the distribution is skewed and the question is about a typical observation rather than a total. Income analysis, request latency, and insurance claim sizes all prefer the weighted median because a handful of extreme values would otherwise dominate the weighted mean.
Interview Questions
Q1: A student earns 4.0 in a 4-credit course and 3.0 in a 1-credit course. What is the GPA?
(4.0 × 4 + 3.0 × 1) / 5 = 19/5 = 3.8. The unweighted average of 3.5 misstates the transcript because it lets the elective match the capstone.
Q2: Why does inverse-variance weighting beat a simple average of two sensors?
Variance falls as one over the weight, so a sensor with three times the standard deviation contributes nine times less precision. Pooling with weights 1/σ² yields the minimum-variance unbiased estimate, pulling the result toward the cleaner instrument.
Q3: What is one property that flags a weighted-mean implementation bug immediately?
The result must lie between the minimum and maximum observations for any non-negative weights. An out-of-range output indicates a wrong denominator — typically dividing by n instead of by the total weight.