Cálculo de la media aritmética (un tipo de promedio) en Python


¿Hay un método de biblioteca incorporado o estándar en Python para calcular la media aritmética (un tipo de promedio) de una lista de números?

Author: jtlz2, 2011-10-10

12 answers

No tengo conocimiento de nada en la biblioteca estándar. Sin embargo, podrías usar algo como:

def mean(numbers):
    return float(sum(numbers)) / max(len(numbers), 1)

>>> mean([1,2,3,4])
2.5
>>> mean([])
0.0

En numpy, hay numpy.mean().

 249
Author: NPE,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-09 07:27:14

NumPy tiene un numpy.mean que es una media aritmética. El uso es tan simple como esto:

>>> import numpy
>>> a = [1, 2, 4]
>>> numpy.mean(a)
2.3333333333333335
 169
Author: Bengt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-13 22:12:28

En Python 3.4, hay un nuevo statistics módulo. Ahora puede utilizar statistics.mean:

import statistics
print(statistics.mean([1,2,4])) # 2.3333333333333335

Para los usuarios 3.1-3.3, la versión original del módulo está disponible en PyPI bajo el nombre stats. Simplemente cambia statistics a stats.

 152
Author: kirbyfan64sos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-28 22:38:12

Ni siquiera necesitas numpy o scipy...

>>> a = [1, 2, 3, 4, 5, 6]
>>> print(sum(a) / len(a))
3
 48
Author: Mumon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-08 15:42:27

Use scipy:

import scipy;
a=[1,2,4];
print(scipy.mean(a));
 8
Author: Elendurwen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-07 01:56:37

En lugar de lanzar a flotar puede hacer lo siguiente

def mean(nums):
    return sum(nums, 0.0) / len(nums)

O usando lambda

mean = lambda nums: sum(nums, 0.0) / len(nums)
 4
Author: Vlad Bezden,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-28 10:56:58
def avg(l):
    """uses floating-point division."""
    return sum(l) / float(len(l))

Ejemplos:

l1 = [3,5,14,2,5,36,4,3]
l2 = [0,0,0]

print(avg(l1)) # 9.0
print(avg(l2)) # 0.0
 1
Author: jasonleonhard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-10 20:29:41
def list_mean(nums):
    sumof = 0
    num_of = len(nums)
    mean = 0
    for i in nums:
        sumof += i
    mean = sumof / num_of
    return float(mean)
 1
Author: Muhoza yves,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-03 11:06:23

Siempre supuse que avg se omite de los builtins / stdlib porque es tan simple como

sum(L)/len(L) # L is some list

Y cualquier advertencia sería abordado en el código de llamada para el uso local ya.

Advertencias notables:

  1. Resultado no flotante: en python2, 9/4 es 2. para resolver, utilice float(sum(L))/len(L) o from __future__ import division

  2. División por cero: la lista puede estar vacía. para resolver:

    if not L:
        raise WhateverYouWantError("foo")
    avg = float(sum(L))/len(L)
    
 0
Author: n611x007,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-02 11:46:50

La respuesta correcta a tu pregunta es usar statistics.mean. Pero por diversión, aquí hay una versión de mean que no usa la función len(), por lo que (como statistics.mean) se puede usar en generadores, que no admiten len():

from functools import reduce
from operator import truediv
def ave(seq):
    return truediv(*reduce(lambda a, b: (a[0] + b[1], b[0]), 
                           enumerate(seq, start=1), 
                           (0, 0)))
 0
Author: PaulMcG,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-29 14:05:21
from statistics import mean
avarage=mean(your_list)

Por ejemplo

from statistics import mean

my_list=[5,2,3,2]
avarage=mean(my_list)
print(avarage)

Y el resultado es

3.0
 0
Author: fariborz najafi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-02 16:56:34

Otros ya han publicado muy buenas respuestas, pero algunas personas todavía podrían estar buscando una forma clásica de encontrar Media (avg), así que aquí posteo esto (código probado en Python 3.6):

def meanmanual(listt):

mean = 0
lsum = 0
lenoflist = len(listt)

for i in listt:
    lsum += i

mean = lsum / lenoflist
return float(mean)

a = [1, 2, 3, 4, 5, 6]
meanmanual(a)

Answer: 3.5
 -1
Author: Hazmat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-11 01:53:03