Statistics Using Python

Calculate mean, median and mode using Python

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.

  1. 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.

wilsonzhang746

Share
Published by
wilsonzhang746
Tags: list

Recent Posts

Download R Course source files

Click here to download R Course source files !

2 months ago

Download Python Course source files

Click here to download Python Course Source Files !

2 months ago

How to create a data frame from nested dictionary with Pandas in Python

For online Python training registration, click here ! Pandas provides flexible ways of generating data…

5 months ago

How to delete columns of a data frame in Python

For online Python training registration, click here ! Data frame is the tabular data object…

5 months ago

Using isin() to check membership of a data frame in Python

Click her for course registration ! When a data frame in Python is created via…

5 months ago

How to assign values to Pandas data frame in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…

5 months ago