Perl 计算一列与另一列聚合的总和

标签 perl hash aggregation

我有一个包含很多列的数据集。我需要做的是将某一列的聚合与另一列的聚合相加。举个例子,

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/

相关文章:

python - Python 3 中的确定性哈希

python - 如何从 perl 调用的 python 传递字符串?

基于字节的 Perl substr

perl:不显眼地写入由 TAP::Formatter::HTML 打开的 IO::Handle

python - 旧的 python 散列从左到右完成——为什么不好?

elasticsearch - 如何过滤 elasticsearch 全局聚合?

regex - Perl 正则表达式 - 我可以说 'if character/string matches, delete it and all to right of it' 吗?

string - 具有输入更改容差阈值的哈希

apache-kafka - 具有自定义对象数据类型的 Kafka Stream 聚合

arrays - 以列值作为键聚合 JSON 数组