计算扁平化 NumPy 数组的中位数
中位数
中位数是表示排序后的数值列表中中间值的集中趋势的统计度量。换句话说,我们可以说中位数是将数据集的上半部分与下半部分分隔开的值。
当元素总数为奇数时,计算中位数的数学公式如下。
Median = (n+1)/2
其中,n 是给定集合中的最后一个元素。
扁平化数组
扁平化是一个降低数组维度的过程。扁平化数组是一个通过扁平化多维数组创建的**一维**数组,其中数组中的所有元素都将连接到一个单行中。
在 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
示例
这是另一个查找 5D 扁平化数组的中位数的示例。
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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP