簡體   English   中英

在 Java 火花 dataframe 中將不同值從幾列連接到一列

[英]Concatenate distinct values from several columns to one column in Java spark dataframe

我有下面的火花 dataframe。

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

My reqired output is a dataframe with single column with duplicates removed from column 2 3 and 5. Column_5 should be filtered and added to output when column_4 is Y. if it's N, then column_5 values should be ignored.

必需 Output Dataframe

Column_1
A
B
F
D
C
G
H

到目前為止我嘗試了什么:

我通過在每列中刪除重復項來做到這一點。 在第 4 列上應用過濾器,最后對所有列進行聯合,以獲得帶有列的最終 output dataframe。

在 Java 火花中有沒有更好的方法來做到這一點。 可能不使用 UDF。

array中添加所需的列和過濾器並explode數據。 你會得到最終的結果。

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         |
+----------+

可以使用每列的聯合:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM