我有一个像这样的数据集 ds
:
ds.show():
id1 | id2 | id3 | value |
1 | 1 | 2 | tom |
1 | 1 | 2 | tim |
1 | 3 | 2 | tom |
1 | 3 | 2 | tom |
2 | 1 | 2 | mary |
我想删除每个键(id1,id2,id3)
的所有重复行(注意:与distinct()不同,我不想仍然有一个不同的行,但要删除两行),预期的输出是:
id1 | id2 | id3 | value |
1 | 3 | 2 | tom |
2 | 1 | 2 | mary |
这里我应该删除第 1 行和第 2 行,因为我们有 2 个键组值。
我尝试使用:
ds.groupBy(id1,id2,id3).distinct()
但它不起作用。
答案 0 :(得分:3)
您可以在 window
上将 filter
函数与 count
一起使用,如下所示
val df = Seq(
(1, 1, 2, "tom"),
(1, 1, 2, "tim"),
(1, 3, 2, "tom"),
(2, 1, 2, "mary")
).toDF("id1", "id2", "id3", "value")
val window = Window.partitionBy("id1", "id2", "id3")
df.withColumn("count", count("value").over(window))
.filter($"count" < 2)
.drop("count")
.show(false)
输出:
+---+---+---+-----+
|id1|id2|id3|value|
+---+---+---+-----+
|1 |3 |2 |tom |
|2 |1 |2 |mary |
+---+---+---+-----+