计算布尔列的百分比

时间:2018-02-03 00:55:02

标签: apache-pig hortonworks-data-platform

假设我的数据具有以下结构:

Year      | Location | New_client 

2018      | Paris    | true
2018      | Paris    | true
2018      | Paris    | false
2018      | London   | true
2018      | Madrid   | true
2018      | Madrid   | false
2017      | Paris    | true

我正在尝试计算每年和每个位置New_client的真值百分比,因此从结构示例中获取记录的示例将是

2018     | Paris    | 66
2018     | London   | 100
2018     | Madrid   | 50
2017     | Paris    | 100

https://stackoverflow.com/a/13484279/2802552改编我当前的脚本但不同之处在于它使用2列(年份和位置)而不是1列

data = load...
grp = group inpt by Year; -- creates bags for each value in col1 (Year)
result = FOREACH grp {
    total = COUNT(data);
    t = FILTER data BY New_client == 'true'; --create a bag which contains only T values
    GENERATE FLATTEN(group) AS Year, total AS TOTAL_ROWS_IN_INPUT_TABLE, 100*(double)COUNT(t)/(double)total AS PERCENTAGE_TRUE_IN_INPUT_TABLE;
};

问题是这使用年份作为参考,而我需要它作为年份和区域。

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

您需要按YearLocation进行分组,这需要进行两次修改。首先,将Location添加到group by语句中。其次,将FLATTEN(group) AS Year更改为FLATTEN(group) AS (Year, Location),因为group现在是一个包含两个字段的元组。

grp = group inpt by (Year, Location);
result = FOREACH grp {
    total = COUNT(inpt);
    t = FILTER inpt BY New_client == 'true';
    GENERATE 
        FLATTEN(group) AS (Year, Location), 
        total AS TOTAL_ROWS_IN_INPUT_TABLE, 
        100*(double)COUNT(t)/(double)total AS PERCENTAGE_TRUE_IN_INPUT_TABLE;
};

答案 1 :(得分:0)

测试了这段代码,看起来对我有用:

A = LOAD ...
B = GROUP A BY (year, location);
C = FOREACH B  {
    TRUE_CNT = FILTER A BY (chararray)new_client == 'true';
    GENERATE group.year, group.location, (int)((float)COUNT(TRUE_CNT) / COUNT(A) * 100);
}

DUMP C;
(2017,Paris,100)
(2018,Paris,66)
(2018,London,100)
(2018,Madrid,50)