Central Tendency
Weighted Mean
Compute the weighted mean: sum each value multiplied by its weight, then
divide by the total weight. Values with larger weights pull the mean toward
them more than values with smaller weights. By hand, accumulate the weighted
sum and total weight in a loop. With numpy, np.average(values, weights=weights)
does both steps in one call.
By hand
With the library
np.average(values, weights=weights) computes the weighted sum and divides
by the total weight in one vectorised call. float() converts the numpy
scalar to a plain Python float before printing.
naive.py
values = [10, 20, 30, 40, 50]
weights = [1, 2, 3, 2, 1]
w_sum = 0.0
total_w = 0.0
for i in range(len(values)):
w_sum = w_sum + values[i] * weights[i]
total_w = total_w + weights[i]
mean = w_sum / total_w
print('RESULT:', round(mean, 10))
library.py
import numpy as np
from dalib.display import set_display
set_display()
values = [10, 20, 30, 40, 50]
weights = [1, 2, 3, 2, 1]
wmean = float(np.average(values, weights=weights))
print('np.average:', wmean)
print('RESULT:', round(wmean, 10))
np.average: 30.0
RESULT: 30.0
Implementation notes
- When all weights are equal, the weighted mean reduces to the arithmetic
mean. With
weights=[1,1,1,1,1]on this data the result would be 30.0 — the same answer, because the values are symmetric around 30. np.averageraisesZeroDivisionErrorif the weights sum to zero; the naive half has the same failure mode atmean = w_sum / total_w.- Cross-reference:
arithmetic-mean(this chapter) for the equal-weight special case and the balance-point property.