powershell - 在 PowerShell 中查找数据集的统计模式

标签 powershell statistics

这个 self 回答的问题是 this question 的后续问题:

如何确定给定数据集(数组)的 statistical mode ,即最常出现的一个值或一组值?

例如,在数组 1, 2, 2, 3, 4, 4, 5 中有两种模式,24 ,因为它们是出现频率最高的值。

最佳答案

结合使用 Group-ObjectSort-Objectdo ... while 循环:

# Sample dataset.
$dataset = 1, 2, 2, 3, 4, 4, 5

# Group the same numbers and sort the groups by member count, highest counts first.
$groups = $dataset | Group-Object | Sort-Object Count -Descending

# Output only the numbers represented by those groups that have 
# the highest member count.
$i = 0
do { $groups[$i].Group[0] } while ($groups[++$i].Count -eq $groups[0].Count)

上面的结果是 24,这是两种模式(出现频率最高的值,在本例中各出现两次),按升序排序(因为 Group-Object按照分组标准进行排序,Sort-Object的排序算法是稳定的。

注意:虽然此解决方案在概念上很简单,但大型数据集的性能可能是一个问题;请参阅底部部分,了解针对某些输入可能进行的优化。

解释:

  • Group-Object按相等性对所有输入进行分组。

  • Sort-Object -Descending按成员计数以降序方式对结果组进行排序(最常出现的输入排在最前面)。

  • do ... while 语句循环排序组并输出每个组代表的输入,只要组成员因此出现次数(频率)最高,正如第一组的成员数所暗示的那样。


性能更好的解决方案,带有字符串和数字:

如果输入元素都是简单的数字或字符串(而不是复杂的对象),则可以进行优化:

  • Group-Object-NoElement 禁止收集每个组中的各个输入。

  • 每个组的 .Name 属性反射(reflect)了分组值,但作为一个字符串,因此必须将其转换回其原始数据类型。

# Sample dataset.
# Must be composed of all numbers or strings.
$dataset = 1, 2, 2, 3, 4, 4, 5

# Determine the data type of the elements of the dataset via its first element.
# All elements are assumed to be of the same type.
$type = $dataset[0].GetType()

# Group the same numbers and sort the groups by member count, highest counts first.
$groups = $dataset | Group-Object -NoElement | Sort-Object Count -Descending

# Output only the numbers represented by those groups that have 
# the highest member count.
# -as $type converts the .Name string value back to the original type.
$i = 0
do { $groups[$i].Name -as $type } while ($groups[++$i].Count -eq $groups[0].Count)

关于powershell - 在 PowerShell 中查找数据集的统计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58738500/

相关文章:

java - Spring 启动中的 hibernate 统计信息不起作用?

r - 计算大 df2 的 F 值

c# - 使用 Powershell 以编程方式清除回收站

powershell - 如果工作完成了怎么办

powershell - 寻求对 Powershell ExpandProperty 行为的解释

java - 放大高低值阻尼器

oracle - 在 Oracle 11g 中复制 Excel 的 CHIDIST 函数

c# - 如何使用Powershell知道dotnet build命令是否出错

xml - 根据父节点的属性选择子节点

python - 将数据帧写入 SQLite 数据库时遇到问题