如何在pyspark中编写嵌套的if else?

Cyb*_*unk 1 pyspark

我有一个 pyspark 数据框,我想达到以下条件:

if col1 is not none:
    if col1 > 17:
       return False
    else:
       return True
    return None 
Run Code Online (Sandbox Code Playgroud)

我通过以下方式实现了它:

out = out.withColumn('col2', out.withColumn(
        'col2', when(col('col1').isNull(), None).otherwise(
            when(col('col1') > 17, False).otherwise(True)
        )))
Run Code Online (Sandbox Code Playgroud)

但是,当我运行此命令时,出现以下错误:

  assert isinstance(col, Column), "col should be Column"
AssertionError: col should be Column
Run Code Online (Sandbox Code Playgroud)

任何想法我可能做错了什么。

Ste*_*ven 7

我认为问题出在你犯的错字上,写了两次out.withColumn

这是我的代码:

from pyspark.sql import functions as F

a = [
    (None,),
    (16,),
    (18,),
]

b = [
    "col1",
]

df = spark.createDataFrame(a, b)

df.withColumn(
    "col2",
    F.when(F.col("col1").isNull(), None).otherwise(
        F.when(F.col("col1") > 17, False).otherwise(True)
    ),
).show()

+----+-----+
|col1| col2|
+----+-----+
|null| null|
|  16| true|
|  18|false|
+----+-----+
Run Code Online (Sandbox Code Playgroud)

您也可以采取一些不同的做法,因为您不需要第一个otherwise或不需要显式评估NULL

df.withColumn(
    "col2",
    F.when(F.col("col1").isNull(), None)
    .when(F.col("col1") > 17, False)
    .otherwise(True),
).show()

# OR

df.withColumn(
    "col2", F.when(F.col("col1") > 17, False).when(F.col("col1") <= 17, True)
).show()
Run Code Online (Sandbox Code Playgroud)