【问题标题】:How can I convert an integer array into one hot encoding in BigQuery?如何在 BigQuery 中将整数数组转换为一种热编码?
【发布时间】:2021-02-20 04:52:43
【问题描述】:

我有一个这样的 BQ 表:

ID  index
A   [1, 3, 4]   
B   [2]
C   [0, 3]
D   [2, 3]

我希望得到一个具有固定长度的单个 one-hot 编码索引列的新表:

ID  index
A   [0, 1, 0, 1, 1]   
B   [0, 0, 1, 0, 0]
C   [1, 0, 0, 1, 0]
D   [0, 0, 1, 1, 0]

这里有一个类似的问题:Transform table to one-hot encoding for many rows,但是转换成多列而不是单列。

【问题讨论】:

    标签: sql google-bigquery


    【解决方案1】:

    在下面使用

    #standardSQL
    with temp as (
      select i from (
        select max(i) as max_index
        from `project.dataset.table` t,
        t.index i
      ), unnest(generate_array(0, max_index)) i
    )
    select id,  
      ( select array_agg(if(i = i1, 1, 0) order by i)
        from temp 
        left join t.index as i1
        on i = i1
      ) index
    from `project.dataset.table` t     
    

    如果将上述应用于您问题中的示例数据

    with `project.dataset.table` as (
      select 'A' id, [1, 3, 4] index union all
      select 'B', [2] union all
      select 'C', [0, 3] union all
      select 'D', [2, 3] 
    )       
    
    • 输出是

    如您所见,它生成一列 - 整数数组
    如果您希望列是字符串类型 - 使用下面而不是 array_agg

    string_agg(if(i = i1, '1', '0') order by i)    
    

    在这种情况下,输出将(非常相似)

    【讨论】:

      猜你喜欢
      • 2021-06-28
      • 1970-01-01
      • 2017-09-21
      • 1970-01-01
      • 2020-08-31
      • 2021-12-18
      • 1970-01-01
      • 2020-01-26
      • 2023-03-13
      相关资源
      最近更新 更多