簡體   English   中英

Perl將行轉置為列

[英]Perl transpose row to column

我一直在尋找一些使用Perl轉置大型csv文件的方法,但是無法在我的循環中正確處理它。

有一個包含7列的標題行(實際上我有200多個列)。 前三列是固定的,后續列是數字。 如果帳戶金額為0,請跳過並且不要進行轉置。

源數據:

Name,Age,Gender,Acct1,Acct2,Acct3,Acct4
Jack,12,M,10,20,0,999
Mary,20,F,40,50,0,111

轉置數據:

Column_ID,Name,Age,Gender,Acct
4,Jack,12,M,10
5,Jack,12,M,20
7,Jack,12,M,999
4,Mary,20,F,40
5,Mary,20,F,50
7,Mary,20,F,111

我猜這個源數據在文件中,而不是手動解析為perl分配。

#!/usr/bin/perl

use strict;
use warnings;

print "Column_ID,Name,Age,Gender,Acct\n";
foreach my $file (@ARGV) {
    open my $FH, '<', $file
    or warn("Couldn't open $file: $!\n"), next;

    while (<$FH>) {
        chomp;
        my @cols = split /\,/;
        my @retained = @rows[0 .. 2];
        foreach my $col (3 .. $#cols) {
            print join(',', 1 + $col, @retained, $cols[$col]) . "\n"
            if $cols[$col];
        }
    }
}

使用Perl單線

$ cat liquan.txt
Name,Age,Gender,Acct1,Acct2,Acct3,Acct4
Jack,12,M,10,20,0,999
Mary,20,F,40,50,0,111
$ perl -F, -lane ' BEGIN { print "Column_ID,Name,Age,Gender,Acct" } for(3..$#F) { if($F[$_]!=0 and $.>1) { print $_+1,",$F[0],$F[1],$F[2],",$F[$_] }}' liquan.txt
Column_ID,Name,Age,Gender,Acct
4,Jack,12,M,10
5,Jack,12,M,20
7,Jack,12,M,999
4,Mary,20,F,40
5,Mary,20,F,50
7,Mary,20,F,111
$

假設您已使用CSV模塊之一將CSV讀入一個數組數組(請不要自己解析CSV),我將這樣進行:

#!/usr/bin/perl
use strict;
use warnings;

my @rows = (
    ['Jack',12,'M',10,20,0,999],
    ['Mary',20,'F',40,50,0,111],
    );

my @output;
foreach my $row (@rows) {
   foreach my $col (3..$#{$row}) {
       if ($row->[$col] != 0) {
           push(@output, [$col + 1, @{$row}[0,1,2,$col]]);
       }
   }
}

foreach my $row (@output) {
    print join(',', @{$row}), "\n";
}

輸出示例:

$ perl dummy.pl
4,Jack,12,M,10
5,Jack,12,M,20
7,Jack,12,M,999
4,Mary,20,F,40
5,Mary,20,F,50
7,Mary,20,F,111

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM