在PySpark isin中包含null

2024-04-18 09:33:09 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的数据帧:

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()

Tags: fromimportfalsetruedfsqlcolnull
3条回答

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

此外,如果希望列为true/false,则可以直接将结果强制转换为布尔值,而无需使用when

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|
+ -+  +   +

尝试以下操作:使用“或”操作测试空值

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()

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|
#+ -+  +   +

相关问题 更多 >