Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

How to get the result based on a condition in spark scala

I have the below dataframe with me

+---+-----+---+
| ID|Month|val|
+---+-----+---+
| M1|  Jan| 10|
| M1|  Feb| 20|
| M1|  Mar| 30|
| M2|  Jan| 22|
| M2|  Feb| 33|
| M3|  Jan| 30|
| M3|  Feb| 30|
| M4|  Jan| 40|
| M4|  Feb| 39|
+---+-----+---+

created by -

val df1=Seq(
("M1","Jan","10"),
("M1","Feb","20"),
("M1","Mar","30"),
("M2","Jan","22"),
("M2","Feb","33"),
("M3","Jan","30"),
("M3","Feb","30"),
("M4","Jan","40"),
("M4","Feb","39")
).toDF("ID","Month","val")

I have to find out those row whose val are lesser than or equal to the previous months.

Expected Result -

+---+-----+---+-------+
| ID|Month|val|    Res|
+---+-----+---+-------+
| M1|  Jan| 10| true  |
| M1|  Feb| 20| true  |
| M1|  Mar| 30| true  |
| M2|  Jan| 22| true  |
| M2|  Feb| 33| true  |
| M3|  Jan| 30| true  |
| M3|  Feb| 30| false |
| M4|  Jan| 40| true  |
| M4|  Feb| 39| false |
+---+-----+---+-------+

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use lag over a window ordered by the month converted to a date:

import org.apache.spark.sql.expressions.Window

val df2 = df1.withColumn(
    "Res",
    coalesce(
        $"val" > lag($"val", 1).over(Window.partitionBy("ID").orderBy(to_date($"Month", "MMM"))),
        lit(true)
    )
).orderBy($"ID", to_date($"Month", "MMM"))

df2.show
+---+-----+---+-----+
| ID|Month|val|  Res|
+---+-----+---+-----+
| M1|  Jan| 10| true|
| M1|  Feb| 20| true|
| M1|  Mar| 30| true|
| M2|  Jan| 22| true|
| M2|  Feb| 33| true|
| M3|  Jan| 30| true|
| M3|  Feb| 30|false|
| M4|  Jan| 40| true|
| M4|  Feb| 39|false|
+---+-----+---+-----+

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...