繁体   English   中英

在 Spark dataframe 中将一行中的值替换为另一行中的值

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM