【问题标题】:Transpose CSV data转置 CSV 数据
【发布时间】:2016-07-31 17:54:23
【问题描述】:

我一直在环顾四周,我可以看到如何将列转换为行,但反之则不行。

Example A

我想要达到的目标如下:

输入数据

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,.....

这是输入数据的一个 sn-p,实际数据有超过 200 个字段(x 轴)

我想要实现的输出如下:

Site Activity, Promotional Activity, Fisclal 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
etc etc

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

#!/usr/local/bin/perl

open file, "EDCNDC-Daily-Volume-Forecast_Ops Forecast by Shift.csv"
        or die $!;    #Opens File or returns error thrown ($!)

while ( <file> ) {

    if ( $. < 4 ) {
        print "";
    }
    elsif ( $. > 8 ) {
        print "";
    }
    elsif ( $_ =~ /^\,\,\,\,/ ) {
        print substr( $_, 4 );
    }
    else {
        print $_;
    }
}

close file

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

【问题讨论】:

  • 似乎与帖子 transpose in perl 以及随后的帖子 transposing-csv-data-in-perl 重复。如果我遗漏了一些关键的区别,请告诉我...?
  • 啊,我一定错过了这些。我将快速阅读这 2 个。
  • 添加到我的重复记录中——Borodin 下面的解决方案在我看来更好。

标签: perl


【解决方案1】:
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
..., ..., ..., ..., .....

【讨论】:

    猜你喜欢
    • 2013-09-14
    • 1970-01-01
    • 2014-07-08
    • 2013-01-30
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多