我有一个包含很多列的数据集。我需要做的是将某一列的聚合与另一列的聚合相加。举个例子,
ID Volume
A 20
D 60
B 10
A 50
K 30
B 100
D 80
所以我想要所有不同 ID(A、B、C...)的总和(按数量计算)并按该总和排序
结果会是这样的
D 140
B 110
A 70
K 30
我如何在 Perl 中完成这个任务?
最佳答案
#!/usr/bin/perl
use strict;
use warnings;
my %ids_and_sums;
while (<>) {
# The regex will only consider one single uppercase letter as
# an ID; in case your IDs may look different, you could prepend
# your 'ID Volume' line with a character which will never be part
# of an ID, and modify below regex to meet your needs
my ($id, $volume) = m/^([A-Z])\s+(\d+)/;
if ($id and $volume) {
$ids_and_sums{$id} += $volume;
}
}
foreach my $key (sort {$ids_and_sums{$b} <=> $ids_and_sums{$a}} keys %ids_and_sums) {
print "$key: $ids_and_sums{$key}\n";
}
打印:
D: 140
B: 110
A: 70
K: 30
编辑:我修改了代码,以便按总和的降序排序。
关于Perl 计算一列与另一列聚合的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4545989/