转置CSV数据

时间:2016-07-31 08:43:38

标签: perl

我一直在四处寻找,我可以看到如何将列转换为行但反之亦然。

Example A

我想要实现的目标如下:

输入数据

interactive_report_id

这是实际数据超过200个字段(x轴)

的输入数据片段

我想要实现的输出如下:

report_id

我当前返回输入格式的代码如下:

Site Activity,MI Report Outage 14:30 - 15:30,03:00 - 09:00 - Level 0 Diverter Installation - SCS Loop,03:00 - 09:00 - Level 1 Diverter Installation - SCS Loop,0,0,...
Promotional Activity,0,0,0,0,0,...
Fiscal week,18,18,18,18,18,...
Week,31,31,31,31,31,...
Date,31/07/2016,01/08/2016,02/08/2016,03/08/2016,04/08/2016,.....

我不得不将CSV转换为可用的格式,因此我限制返回的行。 (第8和11行)

1 个答案:

答案 0 :(得分:2)

use strict;
use warnings 'all';
use feature 'say';

my @data = map {
    chomp;
    [ split /,/ ];
} <DATA>;

for my $i ( 0 .. $#{ $data[0] } ) {
    say join ', ', map { $_->[$i] // "" } @data;
}

__DATA__
Site Activity,MI Report Outage 14:30 - 15:30,03:00 - 09:00 - Level 0 Diverter Installation - SCS Loop,03:00 - 09:00 - Level 1 Diverter Installation - SCS Loop,0,0,...
Promotional Activity,0,0,0,0,0,...
Fiscal week,18,18,18,18,18,...
Week,31,31,31,31,31,...
Date,31/07/2016,01/08/2016,02/08/2016,03/08/2016,04/08/2016,.....

输出

Site Activity, Promotional Activity, Fiscal week, Week, Date
MI Report Outage 14:30 - 15:30, 0, 18, 31, 31/07/2016
03:00 - 09:00 - Level 0 Diverter Installation - SCS Loop, 0, 18, 31, 01/08/2016
03:00 - 09:00 - Level 1 Diverter Installation - SCS Loop, 0, 18, 31, 02/08/2016
0, 0, 18, 31, 03/08/2016
0, 0, 18, 31, 04/08/2016
..., ..., ..., ..., .....