gpt4 book ai didi

scala - 窗口上的 Spark 条件滞后函数

转载 作者:行者123 更新时间:2023-12-02 02:39:17 24 4
gpt4 key购买 nike

我有一个数据框,其中一个值 label(id, bin, date, hour) 相关联:

+----------+----+-----+---+-------------------+
| date|hour| id|bin| label|
+----------+----+-----+---+-------------------+
|2019_12_20| 8| 1| 0| 151.7050821002368|
|2019_12_20| 8| 1| 2| 101.13672140015788|
|2019_12_20| 8| 1| 3| 16.856120233359647|
...

我想在前一天的同一时间、前一天的一个小时前等将多个列附加到与 label 相对应的数据框。我知道如何获得第一个滞后函数:

val dateWindow = Window.partitionBy($"id", $"bin").orderBy($"hour", $"date")
val expandedDf = data.withColumn("yesterdaySameHour", lag($"label", 1, 0.0).over(dateWindow))

但是,我不知道如何在前一天的 hour - 1 获取值 label 。有没有一种方法可以有条件滞后,我可以过滤掉大于或等于当前行小时的 hour ?如果不是,执行此操作的正确方法是什么?

非常感谢。

最佳答案

您必须根据您的目的指定Window 函数。您可能需要两次使用 lag 函数。

import org.apache.spark.sql.expressions.Window

val dW = Window.partitionBy("id", "bin", "hour").orderBy("date")
val hW = Window.partitionBy("id", "bin", "date").orderBy("hour")

df.withColumn("yesterdaySameHour", lag("label", 1, 0.0).over(dW))
.withColumn("todayPreviousHour", lag("label", 1, 0.0).over(hW))
.withColumn("yestedayPreviousHour", lag(lag("label", 1, 0.0).over(dW), 1, 0.0).over(hW))
.orderBy("date", "hour", "bin")
.show(false)

这会给你结果:

+----------+----+---+---+-----+-----------------+-----------------+--------------------+
|date |hour|id |bin|label|yesterdaySameHour|todayPreviousHour|yestedayPreviousHour|
+----------+----+---+---+-----+-----------------+-----------------+--------------------+
|2019_12_19|7 |1 |0 |-1 |0 |0 |0 |
|2019_12_19|7 |1 |2 |-2 |0 |0 |0 |
|2019_12_19|7 |1 |3 |-3 |0 |0 |0 |
|2019_12_19|8 |1 |0 |1 |0 |-1 |0 |
|2019_12_19|8 |1 |2 |2 |0 |-2 |0 |
|2019_12_19|8 |1 |3 |3 |0 |-3 |0 |
|2019_12_20|7 |1 |0 |4 |-1 |0 |0 |
|2019_12_20|7 |1 |2 |5 |-2 |0 |0 |
|2019_12_20|7 |1 |3 |6 |-3 |0 |0 |
|2019_12_20|8 |1 |0 |7 |1 |4 |-1 |
|2019_12_20|8 |1 |2 |8 |2 |5 |-2 |
|2019_12_20|8 |1 |3 |9 |3 |6 |-3 |
+----------+----+---+---+-----+-----------------+-----------------+--------------------+

关于scala - 窗口上的 Spark 条件滞后函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60780299/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com