6.1 Mean and Median
The Mean
The sample mean of a data set is
The population mean of the a set is
numpy syntax for the mean:
import numpy as np
x = [x1,x2,x3,...,xn]
np.mean(x)
Example: find the mean of the data set 1,2,3 using numpy.mean.
- Click
+ Code - Type
import numpy as np - Type
x = [1,2,3] - Type
np.mean(x) - Click
playbutton
import numpy as np
x = [1,2,3]
np.mean(x)
Show expected output
2.0Interpretation: the mean is 2.0
The Median
The median of a data set is the middle number after the data is ordered from smallest to highest.
numpy syntax for median:
import numpy as np
x = [x1,x2,x3,...,xn]
np.median(x)
Example: find the median of the data set 1,2,3,4
import numpy as np
x = [1,2,3,4]
np.median(x)
Show expected output
2.5Interpretation: the median is 2.5
Example: A random sample of 35 annual salaries of Animal Control employees of the City of Chicago is listed below. Write a program to compute the mean, mode and median salaries.
45288, 96096, 69468, 79872, 92520, 49968, 76248, 110076, 84324, 101496, 100668, 66864, 49968, 101496, 49968, 69468, 69468, 96096, 100716, 73380, 52044, 76248, 66864, 66864, 76848, 66864, 139392, 56280, 69468, 66864,73380, 87564, 49968, 49968, 76848
import numpy as np
x= [45288, 96096, 69468, 79872, 92520, 49968, 76248, 110076, 84324, 101496,
100668, 66864, 49968, 101496, 49968, 69468, 69468, 96096, 100716, 73380,
52044, 76248, 66864, 66864, 76848, 66864, 139392, 56280, 69468, 66864,73380,
87564, 49968, 49968, 76848]
print("the mean and median using numpy")
print(np.mean(x))
print(np.median(x))
Show expected output
the mean and median using numpy
75968.91428571429
73380.0Interpretation: The mean is 75968.914286 and the median is 73380.0.
Mode
For mode use np.unique(x,return_counts=True) to display each value with its frequency. Select values with highest frequencies.
Example: What is the mode of x = [1,1,2,2,2,3,3,5,5,5]
import numpy as np
x = [1,1,2,2,2,3,3,5,5,5]
np.unique(x,return_counts=True)
Show expected output
(array([1, 2, 3, 5]), array([2, 3, 2, 3]))Interpretation: From the frequency array ([2, 3, 2, 3]), the and fourth values have the highest frequency 3. Thus, the mode are 2 and 5.
Note: Mode using pandas library is covered in advanced topics here.
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.