现在位置: 首页 > Python 3 教程 > 正文

Python statistics.mode() 方法

Python statistics 模块 Python statistics 模块

Python statistics.mode() 用于计算给定数据集的众数。

语法

statistics.mode() 方法语法如下:

statistics.mode(data)

参数说明:

  • data -- 包含数值的可迭代对象,例如列表或元组。

返回值

函数计算并返回数据集的众数作为结果。

众数是数据集中出现频率最高的值或值的集合。

实例

以下实例演示了 mode() 函数的方法:

实例

import statistics

data = [1, 2, 3, 3, 4, 4, 4, 5]
mode = statistics.mode(data)
print(mode)

输出结果:

4

以上实例中,给定的数据集是 [1, 2, 3, 3, 4, 4, 4, 5],使用 mode() 方法计算出众数为 4。

注意,如果数据集中存在多个众数且频率相同,则 mode() 方法会返回最小的众数。

mode() 方法常用于分析数据集中的集中趋势和常见值。在某些情况下,数据集可能没有众数或存在多个众数,这时可以捕获 statistics.StatisticsError 异常来处理这种情况。

Python statistics 模块 Python statistics 模块