PySpark:when 子句中的多个条件

新手上路,请多包涵

我想修改当前为空白的数据框列 (Age) 的单元格值,只有当另一列 (Survived) 的相应行的值为 0 时,我才会这样做,而 Age 为空白。如果它在 Survived 列中为 1 但在 Age 列中为空白,那么我会将其保留为空。

我尝试使用 && 运算符,但没有用。这是我的代码:

 tdata.withColumn("Age",  when((tdata.Age == "" && tdata.Survived == "0"), mean_age_0).otherwise(tdata.Age)).show()

任何建议如何处理?谢谢。

错误信息:

 SyntaxError: invalid syntax
  File "<ipython-input-33-3e691784411c>", line 1
    tdata.withColumn("Age",  when((tdata.Age == "" && tdata.Survived == "0"), mean_age_0).otherwise(tdata.Age)).show()
                                                    ^

原文由 sjishan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

你得到 SyntaxError 错误异常,因为 Python 没有 && 运算符。 It has and and & where the latter one is the correct choice to create boolean expressions on Column ( | for a logical disjunction and ~ 用于逻辑非)。

您创建的条件也无效,因为它没有考虑 运算符优先级& 在 Python 中的优先级高于 == 所以表达式必须加括号。

 (col("Age") == "") & (col("Survived") == "0")
## Column<b'((Age = ) AND (Survived = 0))'>

旁注 when 函数等同于 case 表达式不是 WHEN 子句。同样的规则仍然适用。连词:

 df.where((col("foo") > 0) & (col("bar") < 0))

析取:

 df.where((col("foo") > 0) | (col("bar") < 0))

您当然可以单独定义条件以避免括号:

 cond1 = col("Age") == ""
cond2 = col("Survived") == "0"

cond1 & cond2

原文由 zero323 发布,翻译遵循 CC BY-SA 3.0 许可协议

pyspark 中,可以使用 & (for and)和 | 构建多个条件(对于或)。

注意:在 pyspark t 中,重要的是将每个表达式括在括号 () 中,这些表达式结合起来形成条件

%pyspark
dataDF = spark.createDataFrame([(66, "a", "4"),
                                (67, "a", "0"),
                                (70, "b", "4"),
                                (71, "d", "4")],
                                ("id", "code", "amt"))
dataDF.withColumn("new_column",
       when((col("code") == "a") | (col("code") == "d"), "A")
      .when((col("code") == "b") & (col("amt") == "4"), "B")
      .otherwise("A1")).show()

在 Spark Scala 代码中,( && ) 或 ( || ) 条件可以在 when 函数中使用

//scala
val dataDF = Seq(
      (66, "a", "4"), (67, "a", "0"), (70, "b", "4"), (71, "d", "4"
      )).toDF("id", "code", "amt")
dataDF.withColumn("new_column",
       when(col("code") === "a" || col("code") === "d", "A")
      .when(col("code") === "b" && col("amt") === "4", "B")
      .otherwise("A1")).show()

=======================

 Output:
+---+----+---+----------+
| id|code|amt|new_column|
+---+----+---+----------+
| 66|   a|  4|         A|
| 67|   a|  0|         A|
| 70|   b|  4|         B|
| 71|   d|  4|         A|
+---+----+---+----------+

此代码片段是从 sparkbyexamples.com 复制的

原文由 vj sreenivasan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题