Calculating arithmetic mean (one type of average) in Python
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()
.
You don't even need numpy or scipy...
>>> a = [1, 2, 3, 4, 5, 6]
>>> print(sum(a) / len(a))
3
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
.
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