首页 > 解决方案 > 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错误。

标签: scaladataframeapache-spark-sql

解决方案


我会使用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|
// +----+----+

推荐阅读