将一些分隔不佳的数据处理为有用的CSV


13

我有一些形式的输出:

count  id     type
588    10 |    3
 10    12 |    3
883    14 |    3
 98    17 |    3
 17    18 |    1
77598    18 |    3
10000    21 |    3
17892     2 |    3
20000    23 |    3
 63    27 |    3
  6     3 |    3
 2446    35 |    3
 14    4 |    3
 15     4 |    1
253     4 |    2
19857     4 |    3
 1000     5 |    3
...

这非常混乱,需要将其清除为CSV,因此我可以将其赠送给项目经理,以便他们从中获得电子表格。

问题的核心是:我需要这样的输出:

id,sum_of_type_1,sum_of_type_2,sum_of_type_3

一个示例是id“ 4”:

14    4 |    3
 15     4 |    1
253     4 |    2
19857     4 |    3

相反,它应该是:

4,15,253,19871

不幸的是,我在这种事情上非常垃圾,我设法将所有行清理干净并转换为CSV,但是我无法对行进行重复数据删除和分组。现在我有这个:

awk 'BEGIN{OFS=",";} {split($line, part, " "); print part[1],part[2],part[4]}' | awk '{ gsub (" ", "", $0); print}'

但是,所有要做的就是清理垃圾字符并再次打印行。

将行按摩到上述输出中的最佳方法是什么?


您甚至想将计数加在一起吗?
hjk

Answers:


12

一种方法是将所有内容都放入哈希中。

# put values into a hash based on the id and tag
awk 'NR>1{n[$2","$4]+=$1}
END{
    # merge the same ids on the one line
    for(i in n){
        id=i;
        sub(/,.*/,"",id);
        a[id]=a[id]","n[i];
    }
    # print everyhing
    for(i in a){
        print i""a[i];
    }
}'

编辑:我的第一个答案未正确回答问题


是的,这样做很好。谢谢!唯一的事情是,我没有考虑到ID中的某些类型为空,从而弄乱了CSV,但我可以解决这些小细节
Paul

@Paul也许会NF<4{$4="no_type";}在开始时添加
DarkHeart'3

11

Perl解救:

#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

<>;  # Skip the header.

my %sum;
my %types;
while (<>) {
    my ($count, $id, $type) = grep length, split '[\s|]+';
    $sum{$id}{$type} += $count;
    $types{$type} = 1;
}

say join ',', 'id', sort keys %types;
for my $id (sort { $a <=> $b } keys %sum) {
    say join ',', $id, map $_ // q(), @{ $sum{$id} }{ sort keys %types };
}

它保留两个表,类型表和id表。对于每个id,它存储每种类型的总和。


5

如果您可以选择GNU datamash,那么

awk 'NR>1 {print $1, $2, $4}' OFS=, file | datamash -t, -s --filler=0 crosstab 2,3 sum 1
,1,2,3
10,0,0,588
12,0,0,10
14,0,0,883
17,0,0,98
18,17,0,77598
2,0,0,17892
21,0,0,10000
23,0,0,20000
27,0,0,63
3,0,0,6
35,0,0,2446
4,15,253,19871
5,0,0,1000

4

Python(pandas尤其是该库非常适合此类工作

data = """count  id     type
588    10 |    3
 10    12 |    3
883    14 |    3
 98    17 |    3
 17    18 |    1
77598    18 |    3
10000    21 |    3
17892     2 |    3
20000    23 |    3
 63    27 |    3
  6     3 |    3
 2446    35 |    3
 14    4 |    3
 15     4 |    1
253     4 |    2
19857     4 |    3
 1000     5 |    3"""

import pandas as pd
from io import StringIO # to read from string, not needed to read from file

df = pd.read_csv(StringIO(data), sep=sep='\s+\|?\s*', index_col=None, engine='python')

这会将csv数据读取到 pandas DataFrame

    count  id  type
0     588  10     3
1      10  12     3
2     883  14     3
3      98  17     3
4      17  18     1
5   77598  18     3
6   10000  21     3
7   17892   2     3
8   20000  23     3
9      63  27     3
10      6   3     3
11   2446  35     3
12     14   4     3
13     15   4     1
14    253   4     2
15  19857   4     3
16   1000   5     3

然后我们将数据分组id,并取列的总和count

df_sum = df.groupby(('type', 'id'))['count'].sum().unstack('type').fillna(0)

重新调整unstack 形状以将id移至列,并fillna用0填充空白字段

df_sum.to_csv()

这返回

id,1,2,3
2,0.0,0.0,17892.0
3,0.0,0.0,6.0
4,15.0,253.0,19871.0
5,0.0,0.0,1000.0
10,0.0,0.0,588.0
12,0.0,0.0,10.0
14,0.0,0.0,883.0
17,0.0,0.0,98.0
18,17.0,0.0,77598.0
21,0.0,0.0,10000.0
23,0.0,0.0,20000.0
27,0.0,0.0,63.0
35,0.0,0.0,2446.0

由于数据框包含丢失的数据(空ID类型组合),因此pandas将ints 转换为float(内部工作方式的限制)。如果您知道输入只能是int,则可以将倒数第二行更改为df_sum = df.groupby(('type', 'id'))['count'].sum().unstack('type').fillna(0).astype(int)


1
您应该解释所提供的代码的功能,这样对看到这篇文章的所有人(而不是这个特定的人)很有帮助。
基金莫妮卡的诉讼

这更清楚吗?我还更正了分隔符的正则表达式
MaartenFabré17年

在我看来很好。感谢您添加解释!
基金莫妮卡的诉讼

3

您可以使用Perl遍历CSV文件并在途中在哈希中累积适当类型的总和。最后,显示为每个ID收集的信息。

数据结构

%h = (
   ID1    =>  [ sum_of_type1, sum_of_type2, sum_of_type3 ],
   ...
)

这有助于理解以下代码:

佩尔

perl -wMstrict -Mvars='*h' -F'\s+|\|' -lane '
   $, = chr 44, next if $. == 1;

   my($count, $id, $type) = grep /./, @F;
   $h{ $id }[ $type-1 ] += $count}{
   print $_, map { $_ || 0 } @{ $h{$_} } for sort { $a <=> $b } keys %h
' yourcsvfile

输出量

2,0,0,17892
3,0,0,6
4,15,253,19871
5,0,0,1000
...

1

我的看法,与别人没太大不同。使用具有数组数组的GNU awk

gawk '
    NR == 1 {next}
    {count[$2][$4] += $1}
    END {
        for (id in count) {
            printf "%d", id
            for (type=1; type<=3; type++) {
                # add zero to coerce possible empty string into a number 
                printf ",%d", 0 + count[id][type]
            }
            print ""        # adds the newline for this line
        }
    }
' file

输出

2,0,0,17892
3,0,0,6
4,15,253,19871
5,0,0,1000
10,0,0,588
12,0,0,10
14,0,0,883
17,0,0,98
18,17,0,77598
21,0,0,10000
23,0,0,20000
27,0,0,63
35,0,0,2446

0

您可以使用此代码根据您的id列汇总值,

我在您的代码后添加了一个awk语句

awk 'BEGIN{OFS=",";} {split($line, part, " "); print part[1],part[2],part[4]}' abcd | awk '{ gsub (" ", "", $0); print}' | awk 'BEGIN{FS=OFS=SUBSEP=","}{arr[$2,$3]+=$1;}END{for ( i in arr ) print i,arr[i];}'

继续这个...

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.