We provide effective and economically affordable training courses for R and Python, click here for more details and course registration !
Mean, median and mode are three statistics that measure the central tendency of numerical data. Mean is the average of sample, and median the mid point of the sample with value sorting from the lowest to the highest, and mode is the value that occur most frequently in the sample. In Python there are various data objects, they can be list, or Numpy ndarray. Here we will show how to calculate mean, median and mode for various data objects in Python.
- Calculating mean, median and mode for list in Python
#mean
testlist = [5,8,22,4,5,13,7,266,1,8,23,14,32,4,7,8,6,9,23,7,8]
def Average(lst):
return sum(lst) / len(lst)
ave = Average(testlist) #mean
ave
Out[2]: 22.857142857142858
#median
testlist.sort()
mid = len(testlist) // 2
midn = (testlist[mid] + testlist[-mid-1]) / 2
midn
Out[3]: 8.0
#mode
from statistics import mode
mode(testlist)
Out[4]: 8
2. Calculation of Mean, median and mode for Numpy array
import numpy as np
#mean
salary = np.random.randint(38, high=60, size=1500)
np.mean(salary)
Out[5]: 48.415333333333336
#median
np.median(salary)
Out[6]: 48.0
#mode
from scipy import stats
stats.mode(salary)
Out[9]: ModeResult(mode=array([58]), count=array([85]))
You can also watch video for Python course from our YouTube Channel.
0 Comments