PySpark-ValueError:无法将列转换为布尔

时间:2019-04-03 10:56:38

标签: pyspark

所以我看过这个解决方案:

ValueError: Cannot convert column into bool

有我认为的解决方案。但是我试图使其与我的数据框一起使用,并且不知道如何实现它。

我的原始代码:

if df2['DayOfWeek']>=6 : 
   df2['WeekendOrHol'] = 1

这给了我错误:

  

无法将列转换为布尔值:请对“和”,“ |”使用“&”对于   构建DataFrame布尔表达式时为'or','〜'为'not'。

因此,根据上面的链接,我尝试了:

from pyspark.sql.functions import when
when((df2['DayOfWeek']>=6),df2['WeekendOrHol'] = 1)   
when(df2['DayOfWeek']>=6,df2['WeekendOrHol'] = 1)

但这是不正确的,因为它也给我一个错误。

2 个答案:

答案 0 :(得分:1)

要根据条件更新列,您需要使用when,如下所示:

from pyspark.sql import functions as F

# update `WeekendOrHol` column, when `DayOfWeek` >= 6, 
# then set `WeekendOrHol` to 1 otherwise, set the value of `WeekendOrHol` to what it is now - or you could do something else. 
# If no otherwise is provided then the column values will be set to None
df2 = df2.withColumn('WeekendOrHol', 
                     F.when(
                        F.col('DayOfWeek') >= 6, F.lit(1)
                     ).otherwise(F.col('WeekendOrHol')
                   )

希望这会有所帮助,祝您好运!

答案 1 :(得分:0)

跳马提供的最佳答案:

df2=df2.withColumn("WeekendOrHol", (df2["DayOfWeek"]>=6).cast("int"))

这是重复的: this