[英]Replace a value in a row with a value in another row in Spark dataframe
我有一个 dataframe 像这样:
ID | 起始值 | 结束值 |
---|---|---|
1 | null | 11a |
1 | 554 | 22b |
2 | null | 33c |
2 | 6743 | 44天 |
假设我们将始终有 2 行具有相同的id
,其中startValue
具有值,另一行startValue
始终为 null。 我想用startValue-10
替换startValue
中的 null 值,其中startValue
取自具有相同 ID 的行,其中startValue
不是 null。
ID | 起始值 | 结束值 |
---|---|---|
1 | 544 | 11a |
1 | 554 | 22b |
2 | 6733 | 33c |
2 | 6743 | 44天 |
示例数据框:
val df = Seq(
("1", null, "11a"),
("1", 554, "22b"),
("2", null, "33c"),
("2", 6743, "44d"),
).toDF("id", "startValue", "endValue")
您可以将空值与在id
的同一分区中找到的另一个startValue
coalesce
,减去 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|
+---+----------+--------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.