Skip to main content
 首页 » 编程设计

scala之Apache Spark,将 “CASE WHEN … ELSE …”计算列添加到现有DataFrame中

2025年02月15日21tintown

我正在尝试使用Scala API将“CASE WHEN ... ELSE ...”计算列添加到现有DataFrame中。
起始数据帧:

color 
Red 
Green 
Blue 

所需的数据帧(SQL语法:CASE WHEN color == Green THEN 1 ELSE 0 END AS bool):
color bool 
Red   0 
Green 1 
Blue  0 

我应该如何实现这种逻辑?

请您参考如下方法:

在即将发布的SPARK 1.4.0版本中(应在 future 几天内发布)。您可以使用when / otherwise语法:

// Create the dataframe 
val df = Seq("Red", "Green", "Blue").map(Tuple1.apply).toDF("color") 
 
// Use when/otherwise syntax 
val df1 = df.withColumn("Green_Ind", when($"color" === "Green", 1).otherwise(0)) 

如果使用的是SPARK 1.3.0,则可以选择使用UDF:
// Define the UDF 
val isGreen = udf((color: String) => { 
  if (color == "Green") 1 
  else 0 
}) 
val df2 = df.withColumn("Green_Ind", isGreen($"color"))