Spark:条件表达式和列操作

Nee*_*eel 4 apache-spark spark-dataframe

我有一个具有以下架构的数据框:

|- colA (Int)
|- colB (Int)
|- cnt  (Int)
Run Code Online (Sandbox Code Playgroud)

我想执行以下条件表达式(伪代码):

if cnt > 1: 
  colC = colA + colB
else: 
  colC = colA
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,colC是用withColumn函数创建的新列。

我不想做一个collectcnt

Psi*_*dom 5

您可以将when/otherwise语法与 结合使用withColumn来有条件地创建列:

df.withColumn("colC", when($"cnt" > 1, $"colA" + $"colB").otherwise($"colA"))
Run Code Online (Sandbox Code Playgroud)