gpt4 book ai didi

python - 在 PySpark isin 中包含 null

转载 作者:行者123 更新时间:2023-12-02 18:55:31 24 4
gpt4 key购买 nike

这是我的数据框:

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)

.isin() 中是否有包含null 的语法?
有点像

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

最佳答案

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

此外,如果你想要一列true/false,你可以直接将结果转换为 bool 值,而无需使用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|
+---+----+------+

关于python - 在 PySpark isin 中包含 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66209128/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com