pyspark - Pyspark:对于每个月,将前 3 个月的累计总和
问题描述
我正在使用 PYSPARK,我正在尝试从特定月份计算过去 3 个月的累积总和:
例子:
Month Value
Jan/19 1
Feb/19 0
Mar/19 4
Apr/19 5
May/19 0
Jun/19 10
因此,前几个月每个月的累计总和将是:
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
我很确定我需要使用窗口和分区功能,但我不知道如何设置它。
谁可以帮我这个事?
谢谢
解决方案
示例数据框:
df.show()
+------+-----+
| Month|Value|
+------+-----+
|Jan/19| 1|
|Feb/19| 0|
|Mar/19| 4|
|Apr/19| 5|
|May/19| 0|
|Jun/19| 10|
+------+-----+
您可以使用window
函数,但您需要将month
列转换为适当的timestamp
格式,然后将其转换为基于orlong
的计算。您可以按真实数据中的分组列进行分区。(86400 是以秒为单位的 1 天)。range(3months)
unix time
timestamp in seconds
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|
+-------------------+-----+---+
如果你想回去3 months only
。each year
意义才会有价值。对于这种情况,您应该使用 a of , and , andJan/19
Jan/19
partitionBy
Year
orderBy month number
rangeBetween -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|
+-------------------+-----+---+
推荐阅读
- python - 如何使用这些规则实现自定义二进制协议?
- excel - ThisWorkbook.close 无法始终如一地工作
- javascript - JSDoc 内联对象类型定义
- vue.js - 等待按钮单击以查找元素 - VueJS/Jest
- javascript - 是否可以使用 fetch API 测量 TTFB
- ios - 如何修复“App Store Connect 操作错误 ITMS-90771”
- python - 如何检查大型 python pandas 数据框是否有重复项(不需要实际的重复行)
- c - if 语句不适用于某些测试用例
- powershell - 在PowerShell中使用二进制比较功能对集合进行排序
- javascript - 在 Angular 中使用选择器时,如何设置组件显示的大小?