如何在pyspark.sql.functions.when()中使用多个条件? [英] How do I use multiple conditions with pyspark.sql.functions.when()?

查看:58
本文介绍了如何在pyspark.sql.functions.when()中使用多个条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有几列的数据框.现在,我想从其他2列中派生一个新列:

I have a dataframe with a few columns. Now I want to derive a new column from 2 other columns:

from pyspark.sql import functions as F
new_df = df.withColumn("new_col", F.when(df["col-1"] > 0.0 & df["col-2"] > 0.0, 1).otherwise(0))

有了这个,我只能得到一个例外:

With this I only get an exception:

py4j.Py4JException: Method and([class java.lang.Double]) does not exist

它仅适用于以下一种情况:

It works with just one condition like this:

new_df = df.withColumn("new_col", F.when(df["col-1"] > 0.0, 1).otherwise(0))

有人知道要使用多个条件吗?

Does anyone know to use multiple conditions?

我正在使用Spark 1.4.

I'm using Spark 1.4.

推荐答案

使用括号强制执行所需的运算符优先级:

Use parentheses to enforce the desired operator precedence:

F.when( (df["col-1"]>0.0) & (df["col-2"]>0.0), 1).otherwise(0)

这篇关于如何在pyspark.sql.functions.when()中使用多个条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆