Python statistics | mean() function
Last Updated :
14 Aug, 2024
Prerequisite : Introduction to Statistical Functions
Python is a very popular language when it comes to data analysis and statistics. Luckily, Python3 provide statistics module, which comes with very useful functions like mean(), median(), mode() etc.
mean() function can be used to calculate mean/average of a given list of numbers. It returns mean of the data set passed as parameters.
Arithmetic mean is the sum of data divided by the number of data-points. It is a measure of the central location of data in a set of values which vary in range. In Python, we usually do this by dividing the sum of given numbers with the count of number present.
Given set of numbers : [n1, n2, n3, n5, n6]
Sum of data-set = (n1 + n2 + n3 + n4 + n5)
Number of data produced = 5
Average or arithmetic mean = (n1 + n2 + n3 + n4 + n5) / 5
Syntax : mean([data-set])
Parameters :
[data-set] : List or tuple of a set of numbers.
Returns : Sample arithmetic mean of the provided data-set.
Exceptions :
TypeError when anything other than numeric values are passed as parameter.
Code #1 : Working
Python3
# Python program to demonstrate mean()
# function from the statistics module
# Importing the statistics module
import statistics
# list of positive integer numbers
data1 = [1, 3, 4, 5, 7, 9, 2]
x = statistics.mean(data1)
# Printing the mean
print("Mean is :", x)
Output :
Mean is : 4.428571428571429
Code #2 : Working
Python3
# Python program to demonstrate mean()
# function from the statistics module
# Importing the statistics module
from statistics import mean
# Importing fractions module as fr
# Enables to calculate mean of a
# set in Fraction
from fractions import Fraction as fr
# tuple of positive integer numbers
data1 = (11, 3, 4, 5, 7, 9, 2)
# tuple of a negative set of integers
data2 = (-1, -2, -4, -7, -12, -19)
# tuple of mixed range of numbers
data3 = (-1, -13, -6, 4, 5, 19, 9)
# tuple of a set of fractional numbers
data4 = (fr(1, 2), fr(44, 12), fr(10, 3), fr(2, 3))
# dictionary of a set of values
# Only the keys are taken in
# consideration by mean()
data5 = {1:"one", 2:"two", 3:"three"}
# Printing the mean of above datasets
print("Mean of data set 1 is % s" % (mean(data1)))
print("Mean of data set 2 is % s" % (mean(data2)))
print("Mean of data set 3 is % s" % (mean(data3)))
print("Mean of data set 4 is % s" % (mean(data4)))
print("Mean of data set 5 is % s" % (mean(data5)))
Output :
Mean of data set 1 is 5.857142857142857
Mean of data set 2 is -7.5
Mean of data set 3 is 2.4285714285714284
Mean of data set 4 is 49/24
Mean of data set 5 is 2
Code #3 : TypeError
Python3
# Python3 code to demonstrate TypeError
# importing statistics module
from statistics import mean
# While using dictionaries, only keys are
# taken into consideration by mean()
dic = {"one":1, "three":3, "seven":7,
"twenty":20, "nine":9, "six":6}
# Will raise TypeError
print(mean(dic))
Output :
Traceback (most recent call last):
File "/home/9f8a941703745a24ddce5b5f6f211e6f.py", line 29, in
print(mean(dic))
File "/usr/lib/python3.5/statistics.py", line 331, in mean
T, total, count = _sum(data)
File "/usr/lib/python3.5/statistics.py", line 161, in _sum
for n, d in map(_exact_ratio, values):
File "/usr/lib/python3.5/statistics.py", line 247, in _exact_ratio
raise TypeError(msg.format(type(x).__name__))
TypeError: can't convert type 'str' to numerator/denominator
Applications :
Mean/Arithmetic average is one of the very important function, while working with statistics and large values. So, with the function like mean(), trending and featured values can be extracted from the large data sets.
Python statistics | mean() function – FAQs
What is mean() in Python?
In Python, mean() is a function typically used to calculate the average of numbers. It is not available in the standard Python library as a standalone function for basic types like lists or tuples, but it is provided through libraries such as numpy and statistics.
Example using the statistics module:
import statistics
# Calculate the mean of a list of numbers
data = [1, 2, 3, 4, 5]
average = statistics.mean(data)
print(average) # Output: 3
What is the Mean Function in Scipy Stats?
In the scipy.stats module, mean() is used to calculate the mean, or average, of data along a specified axis, handling NaN values as specified. Since scipy.stats has deprecated mean(), it’s generally recommended to use numpy.mean() for such calculations.
Example using numpy:
import numpy as np
data = np.array([1, 2, 3, 4, 5])
average = np.mean(data)
print(average) # Output: 3.0
How to Find Average in Python Using Function?
To find the average of numbers in a list in Python using a custom function, you can define a function that sums all the elements and then divides by the number of elements:
def find_average(numbers):
return sum(numbers) / len(numbers) if numbers else 0
data = [1, 2, 3, 4, 5]
average = find_average(data)
print(average) # Output: 3.0
How to Find Mean in Python Without Inbuilt Function?
To calculate the mean of a list without using any built-in functions for mean, you can use basic arithmetic operations provided by Python:
data = [1, 2, 3, 4, 5]
# Calculate mean manually
total = sum(data)
count = len(data)
mean = total / count if count else 0 # Avoid division by zero
print(mean) # Output: 3.0
This method uses sum() and len(), which are Python built-ins for summation and counting elements, respectively.
What Does items() Mean in Python?
The items() method in Python is used with dictionaries to return a view object that displays a list of dictionary’s key-value tuple pairs.
Example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Using items() to iterate through dictionary key-value pairs
for key, value in my_dict.items():
print(f"{key}: {value}")This will output:
a: 1
b: 2
c: 3
This method is particularly useful when you need to access both keys and values while iterating through a dictionary.
Similar Reads
Python statistics | mean() function
Prerequisite : Introduction to Statistical FunctionsPython is a very popular language when it comes to data analysis and statistics. Luckily, Python3 provide statistics module, which comes with very useful functions like mean(), median(), mode() etc.mean() function can be used to calculate mean/aver
5 min read
fmean() function in Python statistics
Statistics module of Python 3.8 provides a function fmean() that converts all the data into float data-type and then computes the arithmetic mean or average of data that is provided in the form of a sequence or an iterable. The output of this function is always a float. The only difference in comput
3 min read
sciPy stats.mean() function | Python
scipy.stats.mean(array, axis=0) function calculates the arithmetic mean of the array elements along the specified axis of the array (list in python). It's formula - Parameters : array: Input array or object having the elements to calculate the arithmetic mean. axis: Axis along which the mean is to b
1 min read
Wand statistic function - Python
The statistic() function is an inbuilt function in the Python Wand ImageMagick library which is used to replace each pixel with the statistic results from neighboring pixel values. The width & height defines the size, or aperture, of the neighboring pixels. Syntax: statistic(stat, width, height,
2 min read
sciPy stats.gmean() function | Python
scipy.stats.gmean(array, axis=0, dtype=None) calculates the geometric mean of the array elements along the specified axis of the array (list in python). It's formula -   Parameters : array: Input array or object having the elements to calculate the geometric mean. axis: Axis along which the mean i
2 min read
mode() function in Python statistics module
The mode of a set of data values is the value that appears most often. It is the value at which the data is most likely to be sampled. A mode of a continuous probability distribution is often considered to be any value x at which its probability density function has a local maximum value, so any pea
5 min read
sciPy stats.nanmean() function | Python
scipy.stats.nanmean(array, axis=0) function calculates the arithmetic mean by ignoring the Nan (not a number) values of the array elements along the specified axis of the array. It's formula - Parameters : array : Input array or object having the elements, including Nan values, to calculate the arit
2 min read
median_low() function in Python statistics module
Median is often referred to as the robust measure of the central location and is less affected by the presence of outliers in data. statistics module in Python allows three options to deal with median / middle elements in a data set, which are median(), median_low() and median_high(). The low median
4 min read
median_high() function in Python statistics module
Median is often referred to as the robust measure of the central location and is less affected by the presence of outliers in data. statistics module in Python allows three options to deal with median / middle elements in a data set, which are median(), median_low() and median_high(). The high media
4 min read
scipy stats.moment() function | Python
scipy.stats.moment(array, axis=0) function calculates the nth moment about the mean for a sample i.e. array elements along the specified axis of the array (list in python). Its formula - Parameters : array : Input array or object having the elements to calculate the moment. axis : Axis along which t
2 min read
Wand mean_shift() function - Python
The mean_shift() function is an inbuilt function in the Python Wand ImageMagick library which is used to recalculate pixel value by comparing neighboring pixels within a color distance and replacing with a mean value. Syntax: mean_shift(width, height, color_distance) Parameters: This function accept
2 min read
median_grouped() function in Python statistics module
Coming to Statistical functions, median of a data-set is the measure of robust central tendency, which is less affected by the presence of outliers in data. As seen previously, medians of an ungrouped data-set using median(), median_high(), median_low() functions. Python gives the option to calculat
4 min read
sciPy stats.nanmedian() function | Python
scipy.stats.nanmedian(array, axis=0) function calculates the median by ignoring the Nan (not a number) values of the array elements along the specified axis of the array. Parameters : array : Input array or object having the elements, including Nan values, to calculate the median. axis : Axis along
2 min read
scipy stats.tmin() function | Python
scipy.stats.tmin(array, lowerlimit=None, axis=0, inclusive=True) function calculates the trimmed minimum of the array elements along with ignoring the values lying outside the specified limits, along the specified axis. Parameters : array: Input array or object having the elements to calculate the m
2 min read
sciPy stats.tsem() function | Python
scipy.stats.tsem(array, limits=None, inclusive=(True, True)) calculates the trimmed standard error of the mean of array elements along the specified axis of the array. Its formula :- Parameters : array: Input array or object having the elements to calculate the trimmed standard error of the mean. ax
2 min read
Python - Normal Distribution in Statistics
A probability distribution determines the probability of all the outcomes a random variable takes. The distribution can either be continuous or discrete distribution depending upon the values that a random variable takes. There are several types of probability distribution like Normal distribution,
6 min read
sum() function in Python
The sum of numbers in the list is required everywhere. Python provides an inbuilt function sum() which sums up the numbers in the list. [GFGTABS] Python arr = [1, 5, 2] print(sum(arr)) [/GFGTABS]Output8 Sum() Function in Python Syntax Syntax : sum(iterable, start) iterable : iterable can be anything
3 min read
sympy.stats.variance() function in Python
In mathematics, the variance is the way to check the difference between the actual value and any random input, i.e variance can be calculated as a squared difference of these two values. With the help of sympy.stats.variance() method, we can calculate the value of variance by using this method. Synt
1 min read
sciPy stats.trimboth() function | Python
scipy.stats.trimboth(a, proportiontocut, axis=0) function slices off the portion of elements in the array from both the ends. Parameters : arr : [array_like] Input array or object to trim. axis : Axis along which the mean is to be computed. By default axis = 0. proportiontocut : Proportion (in range
2 min read