问题描述
背景
假设我有以下数据框:
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
问题
2 - 我怎样才能得到预期的输出?对于我的 pyspark (2.1.0) 版本,似乎没有像 select distinct col1,col2
这样的机制,就像我通过 Impala 所做的那样(例如)。
编辑:
col3 中的输出值对我来说无关紧要。
解决方法
@koilaro 将我导向 '(_(9|31|4|7|_____|U)|/)'
。但是,它不提供在 distinct
中指示列名称的能力。
但是,pyspark 2.1.0
可以胜任:
dropDuplicates
,
另一种方法:
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|
+----+----+
与窗口操作相比,性能明智:
如果您确定您的窗口列 (col1) 没有高度倾斜,那么它会稍微好一些或与此 GroupBy 解决方案相媲美。
但是如果您的 col1
高度倾斜,那么它将无法正确并行化,并且 1 个任务必须完成所有主要操作。在这种情况下,你应该去 groupBy + join