删除与某些行重复的所有行

Remove all rows that are duplicates with respect to some rows

我见过几个这样的问题,但对我的情况没有满意的答案。这是一个示例 DataFrame:

+------+-----+----+
|    id|value|type|
+------+-----+----+
|283924|  1.5|   0|
|283924|  1.5|   1|
|982384|  3.0|   0|
|982384|  3.0|   1|
|892383|  2.0|   0|
|892383|  2.5|   1|
+------+-----+----+

我只想通过 "id""value" 列来识别重复项,然后删除所有实例。

在这种情况下:

输出将是:

+------+-----+----+
|    id|value|type|
+------+-----+----+
|892383|  2.5|   1|
|892383|  2.0|   0|
+------+-----+----+

我试过了

df.dropDuplicates(subset = ['id', 'value'], keep = False)

但是 "keep" 功能不在 PySpark 中(因为它在 pandas.DataFrame.drop_duplicates 中)。

我还能怎么做?

您可以 groupBy idtype 来获取计数。然后使用 join 过滤掉 DataFrame 中计数不为 1 的行:

df.join(
    df.groupBy('id', 'value').count().where('count = 1').drop('count'), on=['id', 'value']
).show()
#+------+-----+----+
#|    id|value|type|
#+------+-----+----+
#|892383|  2.5|   1|
#|892383|  2.0|   0|
#+------+-----+----+

您可以使用 window 函数

from pyspark.sql import Window, functions as F
df.withColumn(
  'fg', 
  F.count("id").over(Window.partitionBy("id", "value"))
).where("fg = 1").drop("fg").show()