apache-spark - 使用 DataFrame 分组的累积总和 - Pyspark
问题描述
我的代码:
df=temp_df.groupBy('date','id').count()
windowval = (Window.partitionBy('date','id').orderBy('date','id').rangeBetween(Window.unboundedPreceding, 0))
final_df = df.withColumn('cum_sum', F.sum('count').over(windowval)).orderBy('date','id').show()
请更正我的代码,我认为使用 Window(rangeBetween) 有问题。
谢谢,
DF:
+-------------------+------------------+-----+
| date| id|count|
+-------------------+------------------+-----+
|2007-11-04 00:00:00| 5| 4|
|2007-11-05 00:00:00| 5| 7|
|2007-11-06 00:00:00| 5| 3|
|2007-11-06 00:00:00| 8| 3|
|2007-11-07 00:00:00| 5| 7|
|2007-11-08 00:00:00| 5| 2|
|2007-11-08 00:00:00| 8| 4|
+-------------------+------------------+-----+
Expected output:
+-------------------+------------------+-----+-------+
| date| id|count|cum_sum|
+-------------------+------------------+-----+-------+
|2007-11-04 00:00:00| 5| 4| 4|
|2007-11-05 00:00:00| 5| 7| 11|
|2007-11-06 00:00:00| 5| 3| 14|
|2007-11-06 00:00:00| 8| 3| 3|
|2007-11-07 00:00:00| 5| 7| 21|
|2007-11-08 00:00:00| 5| 2| 23|
|2007-11-08 00:00:00| 8| 4| 7|
+-------------------+------------------+-----+-------+
My Output:
+-------------------+------------------+-----+-------+
| date| id|count|cum_sum|
+-------------------+------------------+-----+-------+
|2007-11-04 00:00:00| 5| 4| 4|
|2007-11-05 00:00:00| 5| 7| 7|
|2007-11-06 00:00:00| 5| 3| 3|
|2007-11-06 00:00:00| 8| 3| 3|
|2007-11-07 00:00:00| 5| 7| 7|
|2007-11-08 00:00:00| 5| 2| 2|
|2007-11-08 00:00:00| 8| 4| 4|
+-------------------+------------------+-----+-------+
解决方案
只需将您当前的代码更改为:
df = temp_df.groupBy('date', 'id').count()
windowval = Window.partitionBy('id').orderBy('date').rangeBetween(Window.unboundedPreceding, 0)
final_df = df.withColumn('cum_sum', F.sum('count').over(windowval)).orderBy('date', 'id').show()
当您按 id 和 date 进行分区时,每个 ( id
, date
) 组合都是唯一的。您需要按id
and进行分区orderBy
date
推荐阅读
- swift - 类和函数中的 Swift 完成处理程序
- ios - 如何重建开发 pod 更改?
- java - Primefaces Datatable 从支持 bean 滚动到页面
- python - 从 pandas 数据框中,如何找到每个用户的重复评论数?
- python - python django 模型 int() 参数必须是字符串、类似字节的对象或数字而不是日期时间
- ios - 序列化核心数据模型时崩溃
- javascript - 无法在 d3.js 中执行类转换
- erlang - 为什么 Erlang / Elixir 观察者的内存使用数字不加起来?
- python - 在 tensorflow 中设置为 cuda 在 tensorflow 中使用 keras 在 python 中使用 cpu
- matlab - 从两个排序矩阵中创建一个新矩阵