gpt4 book ai didi

python - PySpark:when子句中的多个条件

转载 作者:IT老高 更新时间:2023-10-28 22:10:11 25 4
gpt4 key购买 nike

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

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

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()
^

最佳答案

你得到 SyntaxError 错误异常,因为 Python 没有 && 运算符。它有 and& 后者是在 Column 上创建 bool 表达式的正确选择(| for一个逻辑析取和 ~ 用于逻辑否定)。

您创建的条件也无效,因为它不考虑 operator precedence . 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

关于python - PySpark:when子句中的多个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37707305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com