简体   繁体   中英

PySpark - Upsample / Resample Time Series Data

Is there an efficient way to upsample / resample data that has a frequency about 13-15 minutes to 15 minute frequencies. I have multiple id and 200M+ rows.

dataframe=spark.createDataFrame([("J1", "2019-12-29 12:07:38", 100), ("J1", "2019-12-29 12:24:25", 200), 
                          ("J1", "2019-12-29 12:37:58", 100), ("J8", "2020-09-09 13:06:36", 300), 
                          ("J8", "2020-09-09 13:21:37", 200), ("J8", "2020-09-09 13:36:38", 400)], 
                          ["id", "date_time", "some_value"]).show()

+---+-------------------+----------+
| id|               date|some_value|
+---+-------------------+----------+
| J1|2019-12-29 12:07:38|       100|
| J1|2019-12-29 12:24:25|       200|
| J1|2019-12-29 12:37:58|       100|
| J8|2020-09-09 13:06:36|       300|
| J8|2020-09-09 13:21:37|       200|
| J8|2020-09-09 13:36:38|       400|
+---+-------------------+----------+

Desired Dataframe:

+---+-------------------+----------+
| id|               date|some_value|
+---+-------------------+----------+
| J1|2019-12-29 12:15:00|       100|
| J1|2019-12-29 12:30:00|       200|
| J1|2019-12-29 12:45:00|       100|
| J8|2020-09-09 13:00:00|       300|
| J8|2020-09-09 13:15:00|       200|
| J8|2020-09-09 13:30:00|       400|
+---+-------------------+----------+

There is a function window for that. It generates both start and end . You may need to apply another function to choose the closest.

from pyspark.sql import functions as F

df.withColumn("date_time", F.window("date_time", "15 minutes")["end"]).show()
+---+-------------------+----------+
| id|          date_time|some_value|
+---+-------------------+----------+
| J1|2019-12-29 12:15:00|       100|
| J1|2019-12-29 12:30:00|       200|
| J1|2019-12-29 12:45:00|       100|
| J8|2020-09-09 13:15:00|       300|
| J8|2020-09-09 13:30:00|       200|
| J8|2020-09-09 13:45:00|       400|
+---+-------------------+----------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM