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

mkl*_*nt0 3 statistics powershell

这个自我回答的问题是这个问题的后续问题:

如何确定给定数据集(数组)的统计模式,即最常出现的一个值或一组值?

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

mkl*_*nt0 5

Group-Object使用、Sort-Object和循环的组合do ... 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)
Run Code Online (Sandbox Code Playgroud)

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

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

解释:

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

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

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


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

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

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

  • 每个组的.Name属性都反映分组值,但以string形式进行,因此必须将其转换回其原始数据类型。

# 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)
Run Code Online (Sandbox Code Playgroud)