HOWTO · Python
在 Python 中计算算术平均值
这篇文章解释了 Python 均值的计算方法。它可以使用数学公式或使用 Python 的标准库(如 numpy、statistics 和 scipy)来计算。
本页内容
术语算术平均值是数字的平均值。确定算术平均值的数学公式是将数字之和除以计数。它是在 Python 中通过以下方式确定的。
- 使用数学公式。
- 使用 Python 标准库中的 mean() 函数,例如
NumPy、statistics、scipy。
在 Python 中使用数学公式计算算术平均值
按照这个程序使用数学公式。
listnumbers = [1, 2, 4]
print("The mean is =", sum(listnumbers) / len(listnumbers))
输出:
The mean is = 2.3333333333333335
在 Python 中使用 numpy.mean() 函数计算算术平均值
NumPy 标准库包含用于在 Python 中确定算术平均值的 mean() 函数。为此,首先导入 NumPy 库。请参考下面的示例。
import numpy
listnumbers = [1, 2, 4]
print("The mean is =", numpy.mean(listnumbers))
输出:
The mean is = 2.3333333333333335
在 Python 中使用 statistics.mean() 函数计算算术平均值
statistics 库包含用于确定算术平均值的 mean() 函数。为此,首先导入 statistics 库。请按照以下示例进行操作。
import statistics
listnumbers = [1, 2, 4]
print("The mean is =", statistics.mean(listnumbers))
输出:
The mean is = 2.3333333333333335
在 Python 中使用 scipy.mean() 函数计算算术平均值
scipy 库包含用于确定均值的 mean() 函数。为此,首先导入 scipy 库。这是一个例子。
import scipy
listnumbers = [1, 2, 4]
print("The mean is =", scipy.mean(listnumbers))
输出:
The mean is = 2.3333333333333335