scala - Scala - 用另一列填充“空”列
问题描述
我想在 Scala DataFrames中复制这里提到的问题。我尝试使用以下方法,但到目前为止没有成功。
输入
Col1 Col2
A M
B K
null S
预期产出
Col1 Col2
A M
B K
S <---- S
方法一
val output = df.na.fill("A", Seq("col1"))
该fill
方法不将列作为(第一个)输入。
方法二
val output = df.where(df.col("col1").isNull)
在确定空值后,我找不到合适的方法来调用。
方法 3
val output = df.dtypes.map(column =>
column._2 match {
case "null" => (column._2 -> 0)
}).toMap
我得到一个StringType
错误。
解决方案
我会使用when/otherwise
,如下所示:
import spark.implicits._
import org.apache.spark.sql.functions._
val df = Seq(
("A", "M"), ("B", "K"), (null, "S")
).toDF("Col1", "Col2")
df.withColumn("Col1", when($"Col1".isNull, $"Col2").otherwise($"Col1")).show
// +----+----+
// |Col1|Col2|
// +----+----+
// | A| M|
// | B| K|
// | S| S|
// +----+----+
推荐阅读
- javascript - 如何动态匹配对象值与玩笑
- vue.js - 我想在 VueJs 中制作一个类似收音机的复选框
- firebase - 设备上嵌入式客户端应用程序的身份验证
- json - Google API Places Detail : 不返回日本的地区名称
- javascript - 使用 jQuery 将日期输入值重新格式化为德语格式
- java - 了解 CopyOnWriteArrayList 迭代器行为
- php - 我想在 app.blade.php 中添加到 laravel 主菜单的路由
- javascript - React JS,更新特定字段,从地图呈现
- nginx - 如何在 Nginx 中为与会话持久性相同的客户端 IP 和相同的浏览器进行负载平衡
- python-3.x - 使用 ezdxf 将尺寸线移动到新图层