我想修改当前为空白的数据框列 (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 许可协议
你得到
SyntaxError
错误异常,因为 Python 没有&&
运算符。 It hasand
and&
where the latter one is the correct choice to create boolean expressions onColumn
(|
for a logical disjunction and~
用于逻辑非)。您创建的条件也无效,因为它没有考虑 运算符优先级。
&
在 Python 中的优先级高于==
所以表达式必须加括号。旁注
when
函数等同于case
表达式不是WHEN
子句。同样的规则仍然适用。连词:析取:
您当然可以单独定义条件以避免括号: