【问题标题】:How to use AND or OR condition in when in Spark如何在 Spark 中使用 AND 或 OR 条件
【发布时间】:2017-04-02 21:16:11
【问题描述】:

我想在这种情况下评估两个条件:-

import pyspark.sql.functions as F

df = df.withColumn(
    'trueVal', F.when(df.value < 1 OR df.value2  == 'false' , 0 ).otherwise(df.value)) 

为此,我得到使用“OR”的“无效语法”

即使我尝试使用嵌套的 when 语句:-

df = df.withColumn(
    'v', 
    F.when(df.value < 1,(F.when( df.value =1,0).otherwise(df.value))).otherwise(df.value)
) 

为此,我得到 'keyword can't be an expression' 用于嵌套的 when 语句。

如何在when 中使用多个条件?

【问题讨论】:

  • 这个问题有点老了,但你的'keyword can't be an expression'错误实际上是在内部when中使用单个=而不是==的结果。

标签: apache-spark pyspark apache-spark-sql


【解决方案1】:

pyspark.sql.DataFrame.where 将布尔列作为其条件。使用 PySpark 时,在阅读“列”时考虑“列表达式”通常很有用。

PySpark 列上的逻辑操作使用bitwise operators

  • &amp;and
  • |or
  • ~not

将这些与比较运算符(如&lt;)结合使用时,通常需要括号。

在你的情况下,正确的说法是:

import pyspark.sql.functions as F
df = df.withColumn('trueVal',
    F.when((df.value < 1) | (df.value2 == 'false'), 0).otherwise(df.value))

另见:SPARK-8568

【讨论】:

  • “经常需要括号” - 谢谢 - 这就是我与众不同的原因!
  • 第一个链接应该是when函数,对吧?不是where
  • 您能详细说明为什么 Spark 将列视为表达式吗?
猜你喜欢
  • 2012-06-04
  • 1970-01-01
  • 2016-12-26
  • 2019-02-16
  • 2016-04-24
  • 2019-04-10
  • 2016-12-29
  • 2017-09-09
相关资源
最近更新 更多