当函数给出列对象不可调用时,pyspark用替换列值

pyspark replace column values with when function gives column object is not callable

我有一个table这样的

name
----
A
B
ccc
D
eee

和有效名称列表

legal_names = [A, B, D]

我想用另一个字符串“INVALID”替换所有非法名称。

我使用了这个脚本:

(
    df.withColumn(
        "name",
        F.when((F.col("name").isin(legal_names)), F.col("name")).otherwhise(
            F.lit("INVALID")
        ),
    )
)

但是我得到这个错误


TypeError: 'Column' object is not callable
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
File <command-4397929369165676>:4, in <cell line: 2>()
      1 (
      2     df.withColumn(
      3         "name",
----> 4         F.when((F.col("name").isin(legal_names)), F.col("name")).otherwhise(
      5             F.lit("INVALID")
      6         ),
      7     )
      8 )

TypeError: 'Column' object is not callable

要重现的虚拟数据:

vals = [("A", ), ("B", ), ("ccc", ), ("D", ), ("EEE", )]
cols = ["name"]
legal_names = ["A", "B", "D"]
df = spark.createDataFrame(vals, cols)

尝试使用下面的代码 -

df1 = df.withColumn( "name", F.when( (F.col("name").isin(*legal_names)), F.col("name") ).otherwise(F.lit('INVALID'))  )

输出:

+-------+
|   name|
+-------+
|      A|
|      B|
|INVALID|
|      D|
|INVALID|
+-------+