首页 > 解决方案 > 将一行中的值替换为 Spark 数据框中另一行中的值

问题描述

我有一个像这样的数据框:

ID 起始值 结束值
1 无效的 11a
1 554 22b
2 无效的 33c
2 6743 44天

假设我们将始终有 2 行具有相同的id,其中一个startValue具有值,另一个startValue始终为空。我想替换startValuewith中的空值startValue-10,其中startValueid 取自startValue不为空的具有相同 id 的行。

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")

标签: scalaapache-sparkapache-spark-sql

解决方案


您可以coalesce将空值与startValue在同一分区中找到的其他空值id减去 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|
+---+----------+--------+

推荐阅读