我的資料如下所示:
id,start,expiration,customerid,content
1,13494,17358,0001,whateveriwanthere
2,14830,28432,0001,somethingelsewoo
3,11943,19435,0001,yes
4,39271,40231,0002,makingfakedata
5,01321,02143,0002,morefakedata
在上面的資料中,我想customerid對重疊start和expiration(基本上只是合并間隔)進行分組。我通過按客戶 id 分組,然后在 afirst("start")和上聚合成功地做到了這一點max("expiration")。
df.groupBy("customerid").agg(first("start"), max("expiration"))
但是,這會完全洗掉該id列。我想保存id具有最大過期時間的行。例如,我希望我的輸出如下所示:
id,start,expiration,customerid
2,11934,28432,0001
4,39271,40231,0002
5,01321,02143,0002
我不確定如何為id具有最長到期時間的那一行添加該列。
uj5u.com熱心網友回復:
您可以使用累積條件和以及lag函式來定義group標記重疊行的列。然后,只需按customerid 分組group并獲得 minstart和 max expiration。要獲取id與最大到期日期關聯的值,您可以將此技巧與 struct ordering 一起使用:
import org.apache.spark.sql.expressions.Window
val w = Window.partitionBy("customerid").orderBy("start")
val result = df.withColumn(
"group",
sum(
when(
col("start").between(lag("start", 1).over(w), lag("expiration", 1).over(w)),
0
).otherwise(1)
).over(w)
).groupBy("customerid", "group").agg(
min(col("start")).as("start"),
max(struct(col("expiration"), col("id"))).as("max")
).select("max.id", "customerid", "start", "max.expiration")
result.show
// --- ---------- ----- ----------
//| id|customerid|start|expiration|
// --- ---------- ----- ----------
//| 5| 0002|01321| 02143|
//| 4| 0002|39271| 40231|
//| 2| 0001|11943| 28432|
// --- ---------- ----- ----------
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/412156.html
標籤:
