依人口數計算平均年齡
正如 Jason 在影片中提到的,計算加權平均時,先把每個值乘上其權重後加總,再除以所有權重的加總。
例如,若要用 weights = [2,4,6] 對 data = [10, 30, 50] 求加權平均,我們會計算 $\frac{2 \cdot 10 + 4 \cdot 30 + 6 \cdot 50}{2+4+6}$,也就是 sum(weights * data) / sum(weights)。
不過,在這個練習中,你會搭配使用 func.sum() 與 select,從資料表中選出某欄位的加權平均。你仍會使用 census 資料,並計算 2000 年各州人口加權的年齡平均,接著再依性別分組這個加權平均。
本練習屬於課程
Python 資料庫入門
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import select and func
____
# Select the average of age weighted by pop2000
stmt = select([func.sum(____ * ____) / ____
])