如何在Python中找到平均值、中位数和众数?

均值、中位数和众数是统计学的基本主题。您可以使用Python来轻松计算它们,可以选择使用外部库也可以不使用。

这三个是对于数据集的主要测量方法。中心趋势让我们知道数据集的“正常”或“平均”值。如果您刚开始学习统计学,这是适合您的教程。

通过本教程,您将会:

  • 理解均值、中位数和众数的概念
  • 能够在Python中创建自己的均值、中位数和众数函数
  • 利用Python的statistics模块快速开始使用这些测量方法

如果您想要以下练习的可下载版本,请随时查看GitHub repository.

让我们来看看计算均值、中位数和众数的不同方法。

在Python中计算 均值

算术平均数是中心趋势的最常用测量方法。

请记住,中心趋势是一组数据的典型值。

数据集是一组数据的集合,因此在Python中,数据集可以是以下任何内置数据结构:

  • 列表、元组和集合:对象的集合
  • 字符串:字符的集合
  • 字典:键值对的集合

注意:虽然Python中还有其他数据结构,比如queuesstacks,但我们只使用内置的数据结构。

我们可以通过将数据集的所有值相加,然后将结果除以值的数量来计算均值。例如,如果我们有以下数字列表:

[1, 2, 3, 4, 5, 6]

均值为3.5,因为列表的总和是21,长度为6。21除以6等于3.5。您可以使用以下计算来执行此计算:

(1 + 2 + 3 + 4 + 5 + 6) / 6 = 21

在本教程中,我们将使用一个篮球队的球员作为样本数据。

创建自定义均值函数

让我们首先计算篮球队球员的平均年龄。篮球队的名字将是“Pythonic Machines”。

pythonic_machine_ages = [19, 22, 34, 26, 32, 30, 24, 24]

def mean(dataset):
    return sum(dataset) / len(dataset)

print(mean(pythonic_machine_ages))

对这段代码进行解析:

  • “pythonic_machine_ages”是一个包含篮球运动员年龄的列表
  • 我们定义了一个mean()函数,它返回给定数据集的总和除以数据集的长度
    • sum()函数返回可迭代对象的值的总和,例如列表。尝试将数据集作为参数传递给它,它将返回211
    • len()函数返回可迭代对象的长度,如果将数据集传递给它,您将得到8
  • 我们将篮球队的年龄传递给mean()函数,并打印结果。
  • 如果您检查输出,您将得到:

    26.375
    # 因为 211 / 8 = 26.375

    此输出表示篮球队球员的平均年龄。请注意,该数字不在数据集中,但精确描述了大多数球员的年龄。

    使用Python统计模块中的mean()函数

    计算中心趋势的测量方法是大多数开发者常见的操作。这是因为Python的统计模块提供了多种函数来计算它们,以及其他基本的统计主题。

    由于它是Python standard library的一部分,所以您不需要安装任何外部包。PIP

    以下是您使用此模块的方法:

    from statistics import mean
    
    pythonic_machine_ages = [19, 22, 34, 26, 32, 30, 24, 24]
    
    print(mean(pythonic_machine_ages))

    在上面的代码中,您只需要从statistics 模块中导入mean()函数,并将数据集作为参数传递给它。这将返回与我们在上一节中定义的自定义函数相同的结果:

    26.375

    现在您已经清楚mean的概念了,让我们继续median的测量。

    在Python中找到中位数

    median是排序数据集的中间值。它被用于提供一个确定的population的“典型”值。

    在编程中,我们可以将中位数定义为将序列分为两部分的值-下半部分和上半部分。

    要计算中位数,首先我们需要对数据集进行排序。我们可以使用sorting algorithms或使用内置函数sorted()来完成这一步。第二步是确定数据集的长度是奇数还是偶数。根据这一点,我们将进行以下一些处理:

    • 奇数:中位数是数据集的中间值
    • 偶数:中位数是两个中间值之和除以二

    继续使用我们的篮球队数据集,让我们计算球员的中位数身高(以厘米为单位):

    [181, 187, 196, 196, 198,  203, 207, 211, 215]
    # 由于数据集是奇数,我们选择中间值
    median = 198

    如您所见,由于数据集的长度是奇数,因此我们可以将中间值作为中位数。然而,如果有一个球员刚刚退役,会发生什么呢?

    我们需要计算将数据集的两个中间值作为中位数

    [181, 187, 196, 198, 203, 207, 211, 215] 
    # 我们选择两个中间值,并将其除以2
    median = (198 + 203) / 2
    median = 200.5

    创建自定义中位数函数

    让我们将上述概念实现为Python函数。

    记住我们需要遵循以下三个步骤来获取数据集的中位数:

    • 对数据集进行排序:我们可以使用sorted()函数来完成这个步骤
    • 确定奇数还是偶数:我们可以通过获得数据集的长度并使用模运算符(%)来完成这一步
    • 根据每种情况返回中位数:
      • 奇数:返回中间值
      • 偶数:返回两个中间值的平均值

      这将得到以下函数:

      pythonic_machines_heights = [181, 187, 196, 196, 198, 203, 207, 211, 215]
      after_retirement = [181, 187, 196, 198, 203, 207, 211, 215]
      
      def median(dataset):
          data = sorted(dataset)
          index = len(data) // 2
          
          # 如果数据集是奇数
          if len(dataset) % 2 != 0:
              return data[index]
          
          # 如果数据集是偶数
          return (data[index - 1] + data[index]) / 2

      打印我们数据集的结果:

      print(median(pythonic_machines_heights))
      print(median(after_retirement))

      输出:

      198
      200.5

      请注意,我们在函数开始处创建了一个指向已排序数据库的data变量。虽然上面的列表是排序的,但我们想要创建一个可重复使用的函数,因此每次调用函数时都需要对数据集进行排序。

      索引存储数据集的中间值或上中值,使用整数除法运算符。例如,如果我们传递“pythonic_machine_heights”列表,它将具有值4。

      请记住,在Python中,序列索引从零开始,这是因为我们能够返回列表的中间索引,使用整数除法。

      然后,我们通过将模运算的结果与任何非零值进行比较来检查数据集的长度是否为奇数。如果条件为真,则返回中间元素,例如使用“pythonic_machine_heights”列表:

      >>> pythonic_machine_heights[4]
      # 198

      另一方面,如果数据集是偶数,则返回中间值之和除以二。注意,data[index -1] 给出了数据集的较低中点,而data[index] 提供了数据集的较高中点。

      使用Python统计模块中的median()函数

      这种方法更简单,因为我们使用了statistics模块中已经存在的函数。

      个人而言,如果有人已经为我定义好了某个东西,我会使用它,因为这符合不重复自己(DRY)的原则(在这种情况下,不重复别人的代码)。

      您可以使用以下代码计算前面数据集的中位数:

      from statistics import median
      
      pythonic_machines_heights = [181, 187, 196, 196, 198, 203, 207, 211, 215]
      after_retirement = [181, 187, 196, 198, 203, 207, 211, 215]
      
      print(median(pythonic_machines_heights))
      print(median(after_retirement))

      输出:

      198
      200.5

      计算Python中的众数

      众数是数据集中出现次数最多的值。我们可以将其视为学校的“流行”群体,可能代表所有学生的标准。

      众数的一个示例可以是技术商店的日销售额。该数据集的众数将是特定日销售最高的产品。

      ['laptop', 'desktop', 'smartphone', 'laptop', 'laptop', 'headphones']

      正如您所看到的,上述数据集的众数是“laptop”,因为它是列表中出现频率最高的值。

      有关众数的有趣之处在于,数据集不一定是数值型的。例如,我们可以使用字符串进行计算。

      让我们分析另一天的销售情况:

      ['mouse', 'camera', 'headphones', 'usb', 'headphones', 'mouse']

      上述数据集有两个众数:“mouse”和“headphones”,因为两者的频率都为2。这意味着它是一个多模态数据集。

      如果在数据集中找不到众数,像下面这样:

      ['usb', 'camera', 'smartphone', 'laptop', 'TV']

      这被称为无模态数据集,基本上意味着数据集中没有众数。

      现在您对众数的概念有了一个简单的理解,让我们在Python中计算它。

      创建自定义的众数函数

      我们可以将值的频率视为键值对,换句话说,一个频率字典。

      回顾一下篮球的类比,我们可以使用两个数据集来进行计算:每场比赛的得分和一些球员的球鞋赞助。

      要找到众数,首先我们需要创建一个频率字典,其中包含数据集中出现的每个值,然后获取最大频率,并返回具有该频率的所有元素。

      让我们将其转化为代码:

      points_per_game = [3, 15, 23, 42, 30, 10, 10, 12] sponsorship = [‘nike', ‘adidas', ‘nike', ‘jordan',
      ‘jordan', ‘rebook', ‘under-armour', ‘adidas']

      def mode(dataset):
      frequency = {}

      for value in dataset:
      frequency[value] = frequency.get(value, 0) + 1

      most_frequent = max(frequency.values())

      modes = [key for key, value in frequency.items()
      if value == most_frequent]

      return modes

      print(mode(points_per_game))
      print(mode(sponsorship))

      Output:

      [10] [‘nike', ‘adidas', ‘jordan']

      As you can see, the first print statement gave us a single mode, while the second returned multiple modes.

      Explaining deeper the code above:

      We declare a frequency dictionary
      We iterate over the dataset to create a “frequency” – the statistical term for a set of counters (or frequencies) –
      If the key is found in the dictionary then, it adds one to the value
      If it's not found we create a key-value pair with a value of one
      The most_frequent variable stores – ironically – the biggest value (not key) of the frequency dictionary
      We return the “modes” variable which consists of all the keys in the frequency dictionary with the most frequency.

      Note how important is variable naming to write readable code.

      Using mode() and multimode() from the Python Statistic Module

      Once again the statistics module provides us a quick way to do basic statistics operations.

      We can use two functions: mode() and multimode().

      from statistics import mode, multimode

      points_per_game = [3, 15, 23, 42, 30, 10, 10, 12] sponsorship = [‘nike', ‘adidas', ‘nike', ‘jordan',
      ‘jordan', ‘rebook', ‘under-armour', ‘adidas']

      The code above imports both functions and define the datasets we've been working with.

      Here comes the little difference: The mode() function returns the first mode it encounters, while multimode() returns a list with the most frequent values in the dataset.

      multimode()

      print(mode(points_per_game))
      print(mode(sponsorship))

      Output:

      10
      nike

      Note: In Python 3.8 or greater the mode() function returns the first mode it found. If you have an older version you'll get a StatisticsError.

      Using the multimode() function:

      print(multimode(points_per_game))
      print(multimode(sponsorship))

      Output:

      [10] [‘nike', ‘adidas', ‘jordan']

      To Sum Up

      Congratulations! If you followed so far, you learned how to calculate the mean, median, and mode, the main central tendency measurements.

      Although you can define your custom functions to find mean, median, and mode, it's recommended to use the statistics module, since it's part of the standard library and you need to install nothing to start using it.

      Next, read a friendly introduction to data visualization.

类似文章