Weighted Mean and std
numpy syntax for weighted mean and std:
import numpy as np
x = [x1,x2,x3,...]
w = [w1,w2,w3,...]
np.average(x,weights=w)
numpy sample standard deviation:
import numpy as np
(np.cov(x,aweights=w))**(1/2)
Example: At the end of a term a student received a B in Biology (3 credits), A in History (3 credits), B in English Literature (4 credits), and C in Mathematics (5 credits). Find the students grade point average (GPA). Note: A = 4, B = 3, C = 2, D = 1 F = 0 grade points). GPAs are weighted mean. Find the weighted standard-deviation.
import numpy as np
x = [3,4,3,2]
w = [3,3,4,5]
np.average(x,weights=w)
Show expected output
2.8666666666666667(np.cov(x,aweights=w))**.5
Show expected output
0.8359396992145376Interpretation: The grade point average (GPA) is 2.87 with standard deviation 0.84
Mean and Standard deviation of Grouped Frequency Tables
Sometimes instead of the raw data, we are given a summary frequency table.
Example: Below is a frequency table of quiz scores from 26 students. Find the mean and standard deviation. In this case, we take the midpoint of each class to represent the class score.
| class | midpoint | freq |
|---|---|---|
| 0-2 | 1 | 1 |
| 3-5 | 4 | 6 |
| 6-8 | 7 | 10 |
| 9-11 | 10 | 7 |
| 12-14 | 13 | 0 |
| 15-17 | 16 | 2 |
numpy syntax for mean and std with frequency as weight:
import numpy as np
np.average(x,weights=freq)
numpy sample standard deviation:
import numpy as np
(np.cov(x,fweights=freq),ddof=1)**(1/2)
Example: Below is a frequency table of quiz scores from 26 students. Find the mean and standard deviation. In this case, we take the midpoint of each class to represent the class score.
| class | midpoint | freq |
|---|---|---|
| 0-2 | 1 | 1 |
| 3-5 | 4 | 6 |
| 6-8 | 7 | 10 |
| 9-11 | 10 | 7 |
| 12-14 | 13 | 0 |
| 15-17 | 16 | 2 |
- Click
+ Code - Type
import numpy as np - Type
mid_points = [1,4,7,10,13,16] - Type
freq = [1,6,10,7,0,2] - Type
np.average(mid_points,weights=freq) - Click
playbutton
import numpy as np
mid_points = [1,4,7,10,13,16]
freq = [1,6,10,7,0,2]
np.average(mid_points,weights=freq)
Show expected output
7.576923076923077Interpretation: the mean is 7.576923076923077
import numpy as np
mid_points = [1,4,7,10,13,16]
freq = [1,6,10,7,0,2]
(np.cov(mid_points,fweights=freq,ddof=1))**.5
Show expected output
3.5005494074282333Interpretation: the sample standard deviation is 3.5005494074282333
import numpy as np
mid_points = [1,4,7,10,13,16]
freq = [1,6,10,7,0,2]
np.sqrt(np.cov(mid_points,fweights=freq,ddof=0))
Show expected output
3.432571103225427Interpretation: The population standard deviation is 3.432571103225427
Adapted from Python for Introductory Statistics, by Simon Aman (Truman College, City Colleges of Chicago), licensed under CC BY 4.0. Changes were made: reformatted as an accessible XYZ web edition with live in-browser code cells. License: CC-BY-4.0.