HOWTO · Python

Calculer la moyenne arithmétique en Python

Cet article explique la méthode de calcul de la moyenne Python. Il peut être calculé à l'aide de la formule mathématique ou à l'aide des bibliothèques standard de Python telles que numpy, statistics et scipy.

Sur cette page

Le terme moyenne arithmétique est la moyenne des nombres. La formule mathématique pour déterminer la moyenne arithmétique consiste à diviser la somme des nombres par le nombre. Il est déterminé en Python des manières suivantes.

  • Utilisez la formule mathématique.
  • Utilisez la fonction Mean() des bibliothèques standards de Python comme NumPy, statistics, scipy.

Utilisez la formule mathématique pour calculer la moyenne arithmétique en Python

Suivez ce programme pour utiliser la formule mathématique.

listnumbers = [1, 2, 4]
print("The mean is =", sum(listnumbers) / len(listnumbers))

Production:

The mean is = 2.3333333333333335

Utilisez la fonction numpy.mean() pour calculer la moyenne arithmétique en Python

La bibliothèque standard NumPy contient la fonction mean() utilisée pour déterminer la moyenne arithmétique en Python. Pour cela, importez d’abord la bibliothèque NumPy. Voir l’exemple ci-dessous.

import numpy

listnumbers = [1, 2, 4]
print("The mean is =", numpy.mean(listnumbers))

Production:

The mean is = 2.3333333333333335

Utilisez la fonction statistics.mean() pour calculer la moyenne arithmétique en Python

La bibliothèque statistics contient la fonction mean() utilisée pour déterminer la moyenne arithmétique. Pour cela, importez d’abord la bibliothèque statistics. Suivez l’exemple ci-dessous.

import statistics

listnumbers = [1, 2, 4]
print("The mean is =", statistics.mean(listnumbers))

Production:

The mean is = 2.3333333333333335

Utilisez la fonction scipy.mean() pour calculer la moyenne arithmétique en Python

La bibliothèque scipy contient la fonction mean() utilisée pour déterminer la moyenne. Pour cela, importez d’abord la bibliothèque scipy. Voici un exemple.

import scipy

listnumbers = [1, 2, 4]
print("The mean is =", scipy.mean(listnumbers))

Production:

The mean is = 2.3333333333333335