scala - 将一行中的值替换为 Spark 数据框中另一行中的值
问题描述
我有一个像这样的数据框:
ID | 起始值 | 结束值 |
---|---|---|
1 | 无效的 | 11a |
1 | 554 | 22b |
2 | 无效的 | 33c |
2 | 6743 | 44天 |
假设我们将始终有 2 行具有相同的id
,其中一个startValue
具有值,另一个startValue
始终为空。我想替换startValue
with中的空值startValue-10
,其中startValue
id 取自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")
解决方案
您可以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|
+---+----------+--------+
推荐阅读
- javascript - 如何在状态更新之前检查操作负载?
- spring-boot - 如何阻止 Spring Cloud AWS 机密管理器尝试加载基于配置文件的机密
- c++ - 在 std::stoi 比较字节 0x90 上发现错误
- php - 更新 JSON 对象 PHP
- powerbi - 如何集成本地 Power BI 和 PowerPoint
- java - 如何在 IntelliJ IDEA 控制台输出中隐藏命令行?
- r - 我可以按字母顺序使用字母来表示重复的列而不是 R 中的数字吗?
- ruby - 不使用 Enumerable 类或哈希或映射的 Ruby 置换方法代码
- c# - HttpPost 在 ASP.NET MVC 中返回空模型
- angularjs - 错误:[$injector:unpr] 未知提供者:rProvider <- r <- notificationsBarDirective