QBoard » Statistical modeling » Stats - Tech » Calculating arithmetic mean (one type of average) in Python

Calculating arithmetic mean (one type of average) in Python

  • Is there a built-in or standard library method in Python to calculate the arithmetic mean (one type of average) of a list of numbers?
      August 3, 2020 4:37 PM IST
    0
  • 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().

      August 3, 2020 4:40 PM IST
    0
  • 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
      September 21, 2020 5:00 PM IST
    0
  • 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.
      September 21, 2020 5:01 PM IST
    0
  • You don't even need numpy or scipy...

    >>> a = [1, 2, 3, 4, 5, 6]
    >>> print(sum(a) / len(a))
    3
      September 21, 2020 5:02 PM IST
    0
  • Use scipy:

    import scipy;
    a=[1,2,4];
    print(scipy.mean(a));
     
      September 21, 2020 5:03 PM IST
    0