我有下面的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。
添加所需列&CCD_ 1&CCD_ 2数据。你将得到最终结果。
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