Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

scala - Replace a value in a row with a value in another row in Spark dataframe

I have a dataframe like so:

id startValue endValue
1 null 11a
1 554 22b
2 null 33c
2 6743 44d
question from:https://stackoverflow.com/questions/65905074/replace-a-value-in-a-row-with-a-value-in-another-row-in-spark-dataframe

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

1 Answer

0 votes
by (71.8m points)

You can coalesce the nulls with the other startValue found in the same partition of id, minus 10:

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

val df2 = df.withColumn(
    "startValue",
    coalesce($"startValue", max($"startValue").over(Window.partitionBy("id")) - 10)
)

df2.show
+---+----------+--------+
| id|startValue|endValue|
+---+----------+--------+
|  1|       544|     11a|
|  1|       554|     22b|
|  2|      6733|     33c|
|  2|      6743|     44d|
+---+----------+--------+

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...