未找到 Spark 数据帧中的值 &&:比较空值时



嗨,我有 2 个数据帧df1 和 df2,我基于 id 列加入这 2 个数据帧,然后创建一个新列作为结果并检查下面的测试条件。 1.如果两种情况下的名称相同,则需要设置为Y。 但是,如果任何数据帧中存在任何 null,或者如果两列中都存在 null,则它将显示不匹配。我想要如果两个数据帧中都有 null,那么它应该匹配,所以我添加了以下条件

||(df1("name") is null && df2("name") is null 

因此,如果两列都为 null,那么它应该打印为匹配,但它显示"未找到值"&&"。我正在编写下面的代码。有人可以建议我应该如何实现这一点吗?

df1.join(df2,df2("id") === df2("id"))
.withColumn("Result", when(df1("name") === df2("name") ||
(df1("name") is null && 
(df2("name") is null," matched"))
.otherwise(" Not Matched"))

您忘了在值之前添加)matched

尝试下面的代码。

df1.join(df2,df2("id") === df2("id"))
.withColumn("Result", when((df1("name") === df2("name") || (df1("name").isNull && df2("name").isNull)),"matched").otherwise(" Not Matched"))

为什么要将 df2 中的同一列放在连接条件中?由于两个数据帧上的列名相同,因此只需将列名置于联接条件中即可。 你能尝试更改代码吗- 您的代码-

df1.join(df2,df2("id") === df2("id"))
.withColumn("Result", when(df1("name") === df2("name") ||
(df1("name") is null && 
(df2("name") is null," matched"))
.otherwise(" Not Matched"))

更改为- df2("id"( === df2("id"( 到 "id">

// df2("id") === df2("id") 
df1.join(df2, "id")
.withColumn("Result", when((df1("name") === df2("name") || (df1("name").isNull && df2("name").isNull)),"matched").otherwise(" Not Matched"))

还没有测试过这个,但它应该可以工作。

df1("name") is null不是你需要的函数,is是 scala 中任何对象的方法,你正在寻找df1("name") isNull将返回一个列引用类,它将具有&&方法。

但是查看代码,我建议使用空安全运算符作为<=>在您的情况下,它将简化您的逻辑:

val NullVal = null.asInstanceOf[String]
List(
("hi" , "hi"),
(NullVal, "hi"),
(NullVal, NullVal)
).toDF("c1","c2")
.select($"c1", $"c2", $"c1" === $"c2", $"c1" <=> $"c2")
.show(false)

结果将是

+----+----+---------+-----------+
|c1  |c2  |(c1 = c2)|(c1 <=> c2)|
+----+----+---------+-----------+
|hi  |hi  |true     |true       |
|null|hi  |null     |false      |
|null|null|null     |true       |
+----+----+---------+-----------+

最新更新