我刚刚尝试在窗口上执行countDistinct
,但出现了以下错误:
分析异常:u'不支持唯一的窗口函数:count(distinct color#1926)
有没有办法在pyspark中对窗口进行唯一计数?
这是一些示例代码:
from pyspark.sql.window import Window
from pyspark.sql import functions as F
#function to calculate number of seconds from number of days
days = lambda i: i * 86400
df = spark.createDataFrame([(17, "2017-03-10T15:27:18+00:00", "orange"),
(13, "2017-03-15T12:27:18+00:00", "red"),
(25, "2017-03-18T11:27:18+00:00", "red")],
["dollars", "timestampGMT", "color"])
df = df.withColumn('timestampGMT', df.timestampGMT.cast('timestamp'))
#create window by casting timestamp to long (number of seconds)
w = (Window.orderBy(F.col("timestampGMT").cast('long')).rangeBetween(-days(7), 0))
df = df.withColumn('distinct_color_count_over_the_last_week', F.countDistinct("color").over(w))
df.show()
这是我想要看到的输出:
+-------+--------------------+------+---------------------------------------+
|dollars| timestampGMT| color|distinct_color_count_over_the_last_week|
+-------+--------------------+------+---------------------------------------+
| 17|2017-03-10 15:27:...|orange| 1|
| 13|2017-03-15 12:27:...| red| 2|
| 25|2017-03-18 11:27:...| red| 1|
+-------+--------------------+------+---------------------------------------+
groupBy
和countDistinct
进行聚合,然后再将结果与原始分组的 DataFrame 进行join
。我想知道对于大型集群来说哪种方法更有效? - Jon Deaton