你如何 Window.partitionBy 超过一个范围或条件?

How do you Window.partitionBy over a range or condition?

我有一些按日期时间排序的数据,我想将基于另一列(1 或 0)的值相加。但是,我需要这样做,以便它只在最多 5 秒后对值求和。我该怎么做?

ex Table

|ID  |GPS_TimeStamp         |overG|
---------------------------------
|aa  |2019-08-01 00:18:05.1 |1    |
|aa  |2019-08-01 00:18:06.3 |0    |
|aa  |2019-08-01 00:18:08.4 |1    |
|aa  |2019-08-01 00:18:10.0 |1    |
|aa  |2019-08-01 00:18:11.1 |0    |
|aa  |2019-08-01 00:18:12.2 |0    |
|aa  |2019-08-01 00:18:13.8 |1    |
|aa  |2019-08-01 00:18:16.1 |0    |
---------------------------------

我的无效伪代码如下

myData = myData.withColumn("overG-sum5Seconds", 
   sum(col("overG")).over(Window.partitionBy(
      "GPS_TimeStamp"
   ).orderBy("GPS_TimeStamp").rangeBetween(0, Window.currentRow+timedelta(seconds=5))
   )

结果看起来像

|ID  |GPS_TimeStamp         |overG|overG-sum5Seconds|
---------------------------------------------------
|aa  |2019-08-01 00:18:05.1 |1    |3                |
|aa  |2019-08-01 00:18:06.3 |0    |2                |
|aa  |2019-08-01 00:18:08.4 |1    |3                |
|aa  |2019-08-01 00:18:10.0 |1    |2                |
|aa  |2019-08-01 00:18:11.1 |0    |1                |
|aa  |2019-08-01 00:18:12.2 |0    |1                |
|aa  |2019-08-01 00:18:13.8 |1    |1                |
|aa  |2019-08-01 00:18:16.1 |0    |0                |
---------------------------------------------------

我不能使用滞后或超前,因为并非每一秒都在列表中。所以它必须是基于 GPS_TimeStamp.

的条件

提前致谢

Window函数框架可以解决你的问题。 Window Frames 简而言之,你所要做的就是条件累计和你也可以参考这个答案,How to get cumulative sum

在访问了几个网站后找到了我的答案。

https://www.linkedin.com/pulse/time-series-moving-average-apache-pyspark-laurent-weichberger

原来我想要一个滑动avg/sum

myData = myData.withColumn("unix", (unix_timestamp("GPS_TimeStamp"))+ expr("substr(GPS_TimeStamp,instr(GPS_TimeStamp, '.'))"))
w = (Window.partitionBy("id").orderBy(col("unix")).rangeBetween(0, 5))
myData = myData.withColumn('rolling_sum', sum("overG").over(w))