在 PySpark isin 中包含 null

Including null inside PySpark isin

这是我的数据框:

from pyspark.sql import SparkSession
from pyspark.sql import functions as F

spark = SparkSession.builder.getOrCreate()

dCols = ['c1',  'c2']
dData = [('a', 'b'), 
         ('c', 'd'),
         ('e', None)]     
df = spark.createDataFrame(dData, dCols)

是否有语法将 null 包含在 .isin() 中?

df = df.withColumn(
    'newCol',
    F.when(F.col('c2').isin({'d', None}), 'true')  # <=====?
    .otherwise('false')
).show()

执行代码后我得到

+---+----+------+
| c1|  c2|newCol|
+---+----+------+
|  a|   b| false|
|  c|   d|  true|
|  e|null| false|
+---+----+------+

而不是

+---+----+------+
| c1|  c2|newCol|
+---+----+------+
|  a|   b| false|
|  c|   d|  true|
|  e|null|  true|
+---+----+------+

我想找到一个不需要引用同一列两次的解决方案,而我们现在需要这样做:

(F.col('c2') == 'd') | F.col('c2').isNull()

NULL 不是一个值,但表示没有值,因此您不能将它与 None 或 NULL 进行比较。比较总是会给出错误的。您需要使用 isNull 来检查:

df = df.withColumn(
    'newCol',
    F.when(F.col('c2').isin({'d'}) | F.col('c2').isNull(), 'true')
        .otherwise('false')
).show()

#+---+----+------+
#| c1|  c2|newCol|
#+---+----+------+
#|  a|   b| false|
#|  c|   d|  true|
#|  e|null|  true|
#+---+----+------+

在这种情况下,对该列的一个引用是不够的。要检查空值,您需要使用单独的 isNull 方法。

另外,如果你想要true/false的列,可以不用when直接将结果转为Boolean:

import pyspark.sql.functions as F

df2 = df.withColumn(
    'newCol',
    (F.col('c2').isin(['d']) | F.col('c2').isNull()).cast('boolean')
)

df2.show()
+---+----+------+
| c1|  c2|newCol|
+---+----+------+
|  a|   b| false|
|  c|   d|  true|
|  e|null|  true|
+---+----+------+

试试这个:使用 'or' 操作来测试空值

from pyspark.sql import SparkSession
from pyspark.sql import functions as F
import numpy as np

spark = SparkSession.builder.getOrCreate()

dCols = ['c1',  'c2']
dData = [('a', 'b'), 
         ('c', 'd'),
         ('e', None)]     
df = spark.createDataFrame(dData, dCols)

df = df.withColumn(
    'newCol',
    F.when(F.col('c2').isNull() | (F.col('c2') == 'd'), 'true')   #
    .otherwise('false')
).show()