【问题标题】:Concatenate distinct values from several columns to one column in Java spark dataframe在Java spark数据框中将多列的不同值连接到一列
【发布时间】:2020-11-08 22:36:19
【问题描述】:

我有以下 spark 数据框。

Column_1 Column_2 Column_3 Column_4 Column_5
1        A        A        Y         C
2        B        D        N         E
3        A        C        N         Z
4        F        G        Y         H

我需要的输出是一个数据框,其中包含从第 2、3 和 5 列中删除的重复项。当 column_4 为 Y 时,应过滤 Column_5 并将其添加到输出中。如果为 N,则应忽略 column_5 值。

所需的输出数据帧

Column_1
A
B
F
D
C
G
H

到目前为止我尝试了什么:

我通过在每列中删除重复项来做到这一点。在第 4 列上应用过滤器,最后对所有列进行联合,以获得带有列的最终输出数据框。

在 Java spark 中有没有更好的方法来做到这一点。可能不使用 UDF。

【问题讨论】:

    标签: java dataframe apache-spark


    【解决方案1】:

    arrayexplode 数据中添加所需的列和过滤器。你会得到最终的结果。

    df.show(false)
    +--------+--------+--------+--------+--------+
    |Column_1|Column_2|Column_3|Column_4|Column_5|
    +--------+--------+--------+--------+--------+
    |1       |A       |A       |Y       |C       |
    |2       |B       |D       |N       |E       |
    |3       |A       |C       |N       |Z       |
    |4       |F       |G       |Y       |H       |
    +--------+--------+--------+--------+--------+
    
    
    df
    .select(
        explode(
            array(
                col("Column_2"),
                col("Column_3"), 
                when(col("Column_4") === "Y",col("Column_5")).otherwise(col("Column_2")
            )
        )).as("Column_1")
    )
    .distinct
    .orderBy(col("Column_1").asc)
    .show(false)
    
    +----------+
    | Column_1 |
    +----------+
    |A         |
    |B         |
    |C         |
    |D         |
    |F         |
    |G         |
    |H         |
    +----------+
    

    【讨论】:

    • 谢谢。按预期工作。
    【解决方案2】:

    可以使用每列的联合:

    df.select("Column_2")
      .union(
        df.select("Column_3")
      )
      .union(
        df.select("Column_5").where($"Column_4" === "Y")
      )
      .distinct
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-24
      • 2015-11-16
      • 1970-01-01
      • 1970-01-01
      • 2021-05-09
      • 2020-11-11
      • 2019-12-01
      相关资源
      最近更新 更多