嗨,我有2个数据框df1和df2,我加入这2个基于id列的数据框,然后创建一个新的列作为结果,并检查以下测试条件。 1. 如果名称在两个案例中都相同,那么需要设置为Y。但如果在任何数据框中存在任何null,或者如果两个列中都存在null,那么它将显示不匹配。我想如果两个数据框中都有null,那么它应该被视为匹配,所以我添加了以下条件。
||(df1("name") is null && df2("name") is 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"))
将to-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
将返回一个列引用类,该类将具有的 &&
方法。
但从代码上看,我建议使用null安全操作符作为 <=>
在你的情况下,它将简化你的逻辑。
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 |
+----+----+---------+-----------+