NumPy 计算平铺的数组的中位数

NumPy 计算平铺的数组的中位数

中位数

中位数是表示一组已排序数值中间值的统计度量。换句话说,我们可以说中位数是将数据集的上半部分与下半部分分开的值。

当元素总数为奇数时,计算中位数的数学公式如下。

Median = (n+1)/2

其中n是给定集合的最后一个元素。

平铺数组

平铺是将数组的维度降低的过程。平铺的数组是通过将多维数组平铺成1维数组来创建的,其中数组中的所有元素将串联成一行。

在Numpy中,我们有两个函数ravel()和flatten()来对数组进行平铺。可以使用上述任何一种方法来对给定的多维数组进行平铺。

语法

同样,我们可以使用median()函数来计算数组的中位数。

array.flatten()
np.median(flatten_array)

在下面,

  • Numpy 是库的名称

  • flatten 是用于将给定数组平铺的函数

  • array 是输入数组

  • median 是用于找到给定数组的中位数的函数

  • flatten_array 是保存平铺数组的变量

示例

为了计算数组的中位数,首先我们应该使用flatten()函数将其平铺,然后将结果平铺数组的值传递给median()函数,如以下示例所示:

import numpy as np
a = np.array([[[34,23],[90,34]],[[43,23],[10,34]]])
print("The input array:",a)
flattened_array = a.flatten()
print("The flattened array of the given array:",flattened_array)
med = np.median(flattened_array)
print("The median of the given flattened array:",med)

输出

以下是对展开数组计算得出的中位数的输出。

The input array: [[[34 23]
  [90 34]]

 [[43 23]
  [10 34]]]
The flattened array of the given array: [34 23 90 34 43 23 10 34]
The median of the given flattened array: 34.0

示例

让我们看另一个例子,我们试图计算一个3D数组的中位数 –

import numpy as np
a = np.array([[[23,43],[45,56]],[[24,22],[56,78]]])
print("The input array:",a)
flattened_array = a.flatten()
print("The flattened array of the given 3-d array:",flattened_array)
med = np.median(flattened_array)
print("The median of the given flattened array:",med)

输出

The input array: [[[23 43]
[45 56]]
[[24 22]
[56 78]]]
The flattened array of the given 3-d array: [23 43 45 56 24 22 56 78]
The median of the given flattened array: 44.0

示例

这是在5维扁平数组中找到中位数的另一个例子。

import numpy as np
a = np.array([[[23,43],[45,56]],[[24,22],[56,78]]],ndmin = 5)
print("The input array:",a)
print("The dimension of the array:",np.ndim(a))
flattened_array = a.flatten()
print("The flattened array of the given 3-d array:",flattened_array)
med = np.median(flattened_array)
print("The median of the given flattened array:",med)

输出

The input array: [[[[[23 43]
[45 56]]
[[24 22]
[56 78]]]]]
The dimension of the array: 5
The flattened array of the given 3-d array: [23 43 45 56 24 22 56 78]
The median of the given flattened array: 44.0

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程