1

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

前表

|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 的条件。

提前致谢

4

2 回答 2

1

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

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

原来我想要一个滑动平均/总和

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))
于 2019-10-08T02:48:44.413 回答
0

窗口功能框架可以解决您的问题。窗框 简而言之,您所要做的就是条件累积总和,您也可以参考这个答案,如何获得累积总和

于 2019-10-07T10:40:58.583 回答