我有 DataDrame 看起来像这样:
+-------+---------+
|email |timestamp|
+-------+---------+
|x@y.com| 1|
|y@m.net| 2|
|z@c.org| 3|
|x@y.com| 4|
|y@m.net| 5|
| .. | ..|
+-------+---------+
对于每封电子邮件,我想保留最新记录,因此结果将是:
+-------+---------+
|email |timestamp|
+-------+---------+
|x@y.com| 4|
|y@m.net| 5|
|z@c.org| 3|
| .. | ..|
+-------+---------+
我该怎么做?我是Spark和数据帧的新手。
下面是一个通用的ANSI SQL查询,它应该与Spark SQL一起使用:
SELECT email, timestamp
FROM
(
SELECT t.*, ROW_NUMBER() OVER (PARTITION BY email ORDER BY timestamp DESC) rn
FROM yourTable t
) t
WHERE rn = 1;
对于 PySpark 数据帧代码,请尝试以下操作:
from pyspark.sql.window import Window
df = yourDF
.withColumn("rn", F.row_number()
.over(Window.partitionBy("email")
.orderBy(F.col("timestamp").desc())))
df = df.filter(F.col("rn") == 1).drop("rn")
df.show()