如何计算 pyspark 数据框中某个键的出现次数 (2.1.0)

How to count the number of occurence of a key in pyspark dataframe (2.1.0)

上下文

假设我有以下数据框:

col1 | col2 | col3
a    | toto | 1
a    | toto | 2
a    | toto | 45
a    | toto | 789
a    | toto | 456
b    | titi | 4
b    | titi | 8

col1为主键。

我想知道如何确定 col1 中的哪个键在数据帧中出现次数少于 5 次。

所以输出应该是:

col1 | col2 | col3
b    | titi | 

到目前为止,我想出了以下解决方案:

anc_ref_window = Window.partitionBy("col1")
df\
    .withColumn("temp_one", lit(1)) \
    .withColumn("count", sum(col("temp_one")).over(anc_ref_window)) \
    .drop("temp_one") \
    .filter(col("count") < 5) \
    .drop("count") \
    .show()

给出以下结果:

col1 | col2 | col3
b    | titi | 4
b    | titi | 8

问题

1 - 这是解决问题的正确方法吗?

2 - 我怎样才能得到预期的输出?对于我的 pyspark (2.1.0) 版本,似乎没有像 select distinct col1,col2 这样的机制,就像我通过 Impala (例如)所做的那样。

编辑:

col3 中的输出值对我来说无关紧要。

@koilaro 让我转向 distinct。但是它不提供在 pyspark 2.1.0.

中指示列名称的能力

但是,dropDuplicates 完成了工作:

df\
    .withColumn("temp_one", lit(1)) \
    .withColumn("count", sum(col("temp_one")).over(anc_ref_window)) \
    .drop("temp_one") \
    .filter(col("count") < 5) \
    .drop("count") \
    .dropDuplicates(["col1"])

另一种方法:

df_lessthan5 = df.groupBy(col("col1")).count() \
                 .filter(col("count") < 5) \
                 .drop(col("count"))

df_distinct = df.drop(col("col3")).distinct()

result = df_distinct.join(df_lessthan5, ['col1'], 'inner')

结果:

result.show()
+----+----+
|col1|col2|
+----+----+
|   b|titi|
+----+----+

与 window 操作相比,性能明智:

如果您确定您的 windowed 列 (col1) 没有高度偏斜,那么它会稍微好一些或与此 GroupBy 解决方案相当。

但是,如果您的 col1 是高度偏斜的,那么它将无法正确并行化,并且 1 个任务必须完成所有主要操作。在这种情况下,您应该选择 groupBy + join