apache-spark - PySpark 中字符串和空值比较的难以理解的结果
问题描述
谁能向我解释字符串和空值之间的比较行为。
数据框:
import pyspark.sql.functions as F
df = spark.createDataFrame([
["text_1,","text_1"],
["text_1,","text_2"],
["text_1,",None]
]).toDF("col1", "col2")
df1 = df.withColumn("equal", F.when(F.col("col1") == F.col("col2"), "equal").otherwise("not equal")
+-------+-------+----------+
|col1 |col2 |equal |
+-------+-------+----------+
|text_1 |text_1 |equal |
|text_1 |text_2 |not equal |
|text_1 |null |not equal | <*
+-------+-------+----------+
df2 = df.withColumn("equal", F.when(F.col("col1") != F.col("col2"), "equal").otherwise("not equal")
+-------+-------+----------+
|col1 |col2 |equal |
+-------+-------+----------+
|text_1 |text_1 |equal |
|text_1 |text_2 |not equal |
|text_1 |null |equal | <*
+-------+-------+----------+
比较is equal
似乎进展顺利,但is not equal
出现了问题。
任何人都可以向我解释这个问题,我如何在不检查或用空字符串.isNotNull
填充值的情况下解决这个问题(如果可能)。null
解决方案
您之所以equal
与 null 进行比较,是因为text1 != null
给出了 null,该语句将其解释为 false ,因此您从语句中when
得到了意外。equal
otherwise
您可以使用eqNullSafe
,当其中一列为空时,它返回 False 而不是 null。如果要比较不等式,请使用 的否定~
。eqNullSafe
import pyspark.sql.functions as F
df3 = df.withColumn("equal",
F.when(~F.col("col1").eqNullSafe(F.col("col2")), "not equal")
.otherwise("equal")
)
df3.show()
+------+------+---------+
| col1| col2| equal|
+------+------+---------+
|text_1|text_1| equal|
|text_1|text_2|not equal|
|text_1| null|not equal|
+------+------+---------+
如果你想用空字符串填充空值,你可以使用coalesce
:
import pyspark.sql.functions as F
df4 = df.withColumn("equal",
F.when(F.col("col1") != F.coalesce(F.col("col2"), F.lit("")), "not equal")
.otherwise("equal")
)
df4.show()
+------+------+---------+
| col1| col2| equal|
+------+------+---------+
|text_1|text_1| equal|
|text_1|text_2|not equal|
|text_1| null|not equal|
+------+------+---------+
推荐阅读
- haskell - 为什么 GHC 不能使用实例约束来解决这种统一?
- ios - 进度条 SetProgres
- r - 考虑到控制变量,匹配 R 中的多个数据
- python - PatsyError:错误评估因素:NameError:由于列名中的特殊字符而未定义名称''回归
- discord.js - 我试图找到这个问题的答案,但我没有找到任何答案。我在 Visual Studio Code v1.50.1 上安装 quick.db 时遇到问题
- javascript - 当添加许多列表时,页面会被遮挡。我该如何解决?
- r - 如何在 r 中的列表上应用特定功能?
- karate - 空手道在graphql中替换
- python - 如何在参数解析器中传递文件夹图像目录的路径来测试我的文件夹中的所有图像,而不是只测试一个?
- python - 我正在返回一个 defaultdict(list),但在两者之间随机选择,为什么有时它什么也不返回?