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

Fine tuning a Hugging Face transformer model for multi-track music generation

To train a PyTorch Transformer for multi-track music generation, the standard paradigm is to convert…

3 weeks ago

what are Transformer, LLM , and GPT

In the field of AI and Natural Language Processing (NLP), The Transformer is the engine…

3 weeks ago

Main framework for PyTorch music generation model

If your goal is purely symbolic melody generation (e.g., generating MIDI files or notes rather…

4 weeks ago

affine_grid() in pytorch

According to PyTorch document, In PyTorch, torch.nn.functional.affine_grid generates a 2D or 3D flow field (sampling…

3 months ago

How to create an Android mobile app with a deep learning AI model ?

Creating an Android mobile app with a deep learning AI model involves several key steps:…

12 months ago

Download source files for R Machine learning

Click here to go to source files for R Machine Learning

1 year ago