pyspark window 组的最小(日期)和最大(日期)
pyspark window min(date) and max(date) of group
我有数据集
user
date
loc
a
2021-01-01
1
a
2021-01-02
1
a
2021-01-03
2
a
2021-01-04
2
a
2021-01-05
1
a
2021-01-06
1
我想以
结束
user
startdate
enddate
loc
a
2021-01-01
2021-01-02
1
a
2021-01-03
2021-01-04
2
a
2021-01-05
2021-01-06
1
我已经尝试 window 分区 [user,loc].order by date
row_number
我尝试滞后检查 prevrow loc = current loc 然后增加值
但我被困住了。
有没有人能解决这个分组问题。不知道为什么我这么难弄明白
感谢您的帮助
这是解决问题的一种方法
- 创建一个辅助
group
列来区分 loc
中每个 user
中的连续行
- 然后按
user
、loc
和 group
列对数据帧进行分组,并使用 min
和 max
聚合列 date
- 删除
group
列并按 startdate
对数据框进行排序
w = Window.partitionBy('user').orderBy('date')
b = F.lag('loc').over(w) != F.col('loc')
(
df.withColumn('group', b.cast('int'))
.fillna(0, 'group')
.withColumn('group', F.sum('group').over(w))
.groupBy('user', 'loc', 'group')
.agg(F.min('date').alias('startdate'),
F.max('date').alias('enddate'))
.drop('group')
.orderBy('startdate')
)
+----+---+----------+----------+
|user|loc| startdate| enddate|
+----+---+----------+----------+
| a| 1|2021-01-01|2021-01-02|
| a| 2|2021-01-03|2021-01-04|
| a| 1|2021-01-05|2021-01-06|
+----+---+----------+----------+
我有数据集
user | date | loc |
---|---|---|
a | 2021-01-01 | 1 |
a | 2021-01-02 | 1 |
a | 2021-01-03 | 2 |
a | 2021-01-04 | 2 |
a | 2021-01-05 | 1 |
a | 2021-01-06 | 1 |
我想以
结束user | startdate | enddate | loc |
---|---|---|---|
a | 2021-01-01 | 2021-01-02 | 1 |
a | 2021-01-03 | 2021-01-04 | 2 |
a | 2021-01-05 | 2021-01-06 | 1 |
我已经尝试 window 分区 [user,loc].order by date row_number 我尝试滞后检查 prevrow loc = current loc 然后增加值 但我被困住了。 有没有人能解决这个分组问题。不知道为什么我这么难弄明白
感谢您的帮助
这是解决问题的一种方法
- 创建一个辅助
group
列来区分loc
中每个user
中的连续行
- 然后按
user
、loc
和group
列对数据帧进行分组,并使用min
和max
聚合列date
- 删除
group
列并按startdate
对数据框进行排序
w = Window.partitionBy('user').orderBy('date')
b = F.lag('loc').over(w) != F.col('loc')
(
df.withColumn('group', b.cast('int'))
.fillna(0, 'group')
.withColumn('group', F.sum('group').over(w))
.groupBy('user', 'loc', 'group')
.agg(F.min('date').alias('startdate'),
F.max('date').alias('enddate'))
.drop('group')
.orderBy('startdate')
)
+----+---+----------+----------+
|user|loc| startdate| enddate|
+----+---+----------+----------+
| a| 1|2021-01-01|2021-01-02|
| a| 2|2021-01-03|2021-01-04|
| a| 1|2021-01-05|2021-01-06|
+----+---+----------+----------+