tha*_*les 3 window cumulative-sum partition pyspark
我正在使用 PYSPARK 并且我正在尝试从特定月份计算过去 3 个月的累计总和:
例子:
Month Value
Jan/19 1
Feb/19 0
Mar/19 4
Apr/19 5
May/19 0
Jun/19 10
Run Code Online (Sandbox Code Playgroud)
因此,前几个月每个月的累计金额将是:
Month Value
Jan/19 1
Feb/19 1 + 0 = 1
Mar/19 1+0+4 = 5
Apr/19 0+4+5 = 9
May/19 4+5+0 = 9
Jun/19 5+0+10 = 15
Run Code Online (Sandbox Code Playgroud)
我很确定我需要使用窗口和分区函数,但我不知道如何设置它。
谁可以帮我这个事?
谢谢
示例数据帧:
df.show()
+------+-----+
| Month|Value|
+------+-----+
|Jan/19| 1|
|Feb/19| 0|
|Mar/19| 4|
|Apr/19| 5|
|May/19| 0|
|Jun/19| 10|
+------+-----+
Run Code Online (Sandbox Code Playgroud)
您可以使用window函数,但您需要将month列转换为正确的timestamp格式,然后将其转换long为range(3months)基于unix time或进行计算timestamp in seconds。您可以通过实际数据中的分组列进行分区。(86400 是以秒为单位的 1 天)。
from pyspark.sql import functions as F
from pyspark.sql.window import Window
w=Window().orderBy(F.col("Month").cast("long")).rangeBetween(-(86400*89), 0)
df\
.withColumn("Month", F.to_timestamp("Month","MMM/yy"))\
.withColumn("Sum", F.sum("Value").over(w)).show()
+-------------------+-----+---+
| Month|Value|Sum|
+-------------------+-----+---+
|2019-01-01 00:00:00| 1| 1|
|2019-02-01 00:00:00| 0| 1|
|2019-03-01 00:00:00| 4| 5|
|2019-04-01 00:00:00| 5| 9|
|2019-05-01 00:00:00| 0| 9|
|2019-06-01 00:00:00| 10| 15|
+-------------------+-----+---+
Run Code Online (Sandbox Code Playgroud)
如果你想回去3 months only在each year。意义只有价值。对于这种情况,您应该使用 a of , and , andJan/19Jan/19partitionByYearorderBy month numberrangeBetween -2 and 0.
w=Window().partitionBy(F.year("Month")).orderBy(F.month("Month")).rangeBetween(-2, 0)
df\
.withColumn("Month", F.to_timestamp("Month","MMM/yy"))\
.withColumn("Sum", F.sum("Value").over(w)).show()
+-------------------+-----+---+
| Month|Value|Sum|
+-------------------+-----+---+
|2019-01-01 00:00:00| 1| 1|
|2019-02-01 00:00:00| 0| 1|
|2019-03-01 00:00:00| 4| 5|
|2019-04-01 00:00:00| 5| 9|
|2019-05-01 00:00:00| 0| 9|
|2019-06-01 00:00:00| 10| 15|
+-------------------+-----+---+
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
927 次 |
| 最近记录: |