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.
The arithmetic mean is the simplest and most widely used measure of a mean, or average. It simply involves taking the sum of a group of numbers, then dividing that sum by the count of the numbers used in the series. For example, take the numbers 34, 44, 56, and 78.
Average can simply be defined as the sum of all the numbers divided by the total number of values. A mean is defined as the mathematical average of the set of two or more data values. Average is usually defined as mean or arithmetic mean. Mean is simply a method of describing the average of the sample.
I am not aware of anything in the standard library. However, you could use something like:
def mean(numbers):
return float(sum(numbers)) / max(len(numbers), 1)
>>> mean([1,2,3,4])
2.5
>>> mean([])
0.0
In numpy, there's numpy.mean()
.
NumPy has a numpy.mean
which is an arithmetic mean. Usage is as simple as this:
>>> import numpy
>>> a = [1, 2, 4]
>>> numpy.mean(a)
2.3333333333333335
Use statistics.mean
:
import statistics
print(statistics.mean([1,2,4])) # 2.3333333333333335
It's available since Python 3.4. For 3.1-3.3 users, an old version of the module is available on PyPI under the name stats
. Just change statistics
to stats
.
You don't even need numpy or scipy...
>>> a = [1, 2, 3, 4, 5, 6]
>>> print(sum(a) / len(a))
3
Use scipy:
import scipy;
a=[1,2,4];
print(scipy.mean(a));
Instead of casting to float you can do following
def mean(nums):
return sum(nums, 0.0) / len(nums)
or using lambda
mean = lambda nums: sum(nums, 0.0) / len(nums)
UPDATES: 2019-12-15
Python 3.8 added function fmean to statistics module. Which is faster and always returns float.
Convert data to floats and compute the arithmetic mean.
This runs faster than the mean() function and it always returns a float. The data may be a sequence or iterable. If the input dataset is empty, raises a StatisticsError.
fmean([3.5, 4.0, 5.25])
4.25
New in version 3.8.
from statistics import mean
avarage=mean(your_list)
for example
from statistics import mean
my_list=[5,2,3,2]
avarage=mean(my_list)
print(avarage)
and result is
3.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With