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 source files for R Machine learning

Click here to go to source files for R Machine Learning

4 days ago

Python Machine Learning Source Files

Click here to download Python Machine Learning Source Files !

4 weeks ago

Install PyTorch on Windows

PyTorch is a deep learning package for machine learning, or deep learning in particular for…

1 month ago

Topic Modeling using Latent Dirichlet Allocation with Python

Topic modeling is a subcategory of unsupervised machine learning method, and a clustering task in…

2 months ago

Document sentiment classification using bag-of-words in Python

For online Python training registration, click here ! Sentiment classification is a type of machine…

2 months ago

Download R Course source files

Click here to download R Course source files !

11 months ago