尝试计算自用户首次开始使用应用程序以来经过的天数以及 df 行代表的事件。下面的代码 ( via ) 创建一个列,将该行与上一行进行比较,但我需要将其与分区的第一行进行比较。
window = Window.partitionBy('userId').orderBy('dateTime')
df = df.withColumn("daysPassed", datediff(df.dateTime,
lag(df.dateTime, 1).over(window)))
尝试用“int(Window.unboundedPreceding)”代替 1,这会引发错误。
我希望 daysPassed 列执行的操作示例:
Row(userId='59', page='NextSong', datetime='2018-10-01', daysPassed=0),
Row(userId='59', page='NextSong', datetime='2018-10-03', daysPassed=2),
Row(userId='59', page='NextSong', datetime='2018-10-04', daysPassed=3)
最佳答案
所以,如果我做对了,本质上你想要计算行中的日期与用户的最小日期(开始日期)的差异,而不是 lag()
.
from pyspark.sql import functions as func
window = Window.partitionBy('userId')
df_b = df_a.withColumn("daysPassed", func.datediff(df.dateTime, func.min(df.dateTime).over(window)))
这会计算从用户首次启动应用程序之日起的天数。
关于python - 如何使用窗口函数计算pyspark中的日期差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59260218/