我正在尝试在pyspark数据框中检查条件并将值添加到如下所示的列中:
DF:
cd id Location
A A A
A AA A
A AAA
A B B
A BB B
A BBB
预期输出:
cd id Location
A A A
A AA A
A AAA New_Loc
A B B
A BB B
A BBB New_Loc
我尝试使用下面的pyspark转换填充
df_new = df.withColumn('Location',sf.when(df.cd == 'A' & (df.id isin(['AAA','BBB'])),'New_Loc').otherwise(df.Location))
当我尝试执行此操作时,出现错误: Py4JError:调用o129.and时发生错误。跟踪:py4j.Py4JException:方法和[[class java.lang.string])不存在
知道这个错误是什么吗?
答案 0 :(得分:2)
最有可能是语法。这应该起作用:
import pyspark.sql.functions as f
df_new = df.withColumn(
'Location',
f.when(
(f.col('cd') == 'A') & (f.col('id').isin(['AAA','BBB'])),
f.lit('New_Loc'))
.otherwise(f.col('Location'))
)
答案 1 :(得分:-1)
好吧..在工作条件周围加上一个括号。
下面是对我有用的。
df_new = df.withColumn('Location',sf.when((df.cd == 'A') & (df.id isin(['AAA','BBB'])),'New_Loc').otherwise(df.Location))