如何调用在Scala数据帧中返回int的函数并将其追加

如何调用在Scala数据帧中返回int的函数并将其追加,scala,apache-spark,dataframe,Scala,Apache Spark,Dataframe,我有一个像这样的数据帧 x y _ _ 1 10 2 30 3 50 4 24 5 36 6 45 我想附加另一列z,它将取决于y的值 所以我创建了一个函数 def GiveNumVal(col: Column) => Integer = { if(Column>=0 && Column<15){ return 1; } else if(Column>=15 &&

我有一个像这样的数据帧

x  y
_  _
1  10
2  30
3  50
4  24
5  36 
6  45
我想附加另一列z,它将取决于y的值

所以我创建了一个函数

def  GiveNumVal(col: Column) => Integer = {

      if(Column>=0 && Column<15){
        return 1;
      }
      else if(Column>=15 && Column<30){
        return 2;
      }
      else if(Column>=30 && Column<45){
        return 3;
      }

     else if (Column>=45 && Column<=59){
        return 4;
      }
      else{
        return 0;
      }
    }

它甚至不能编译。我不确定哪里是错误的部分。非常感谢您的帮助。

您需要注册要使用的
udf
,或者创建一个像这样的
udf

import org.apache.spark.sql.functions._
// create dataframe
val df = Seq(
  (1, 10),
  (2, 30),
  (3, 50),
  (4, 24),
  (5, 36),
  (6, 45)
).toDF("x", "y")

//create udf 
def giveNumVal = udf((c : Int) => {
  if(c >=0 && c <15) 1
  else if(c >=15 && c <30) 2
  else if(c >=30 && c <45) 3
  else if (c >=45 && c <=59) 4
  else 0
})
如果您有一个通用函数,并且希望用作udf,那么您可以注册为

//general function 
  def giveNumVal = (c : Int) => {
    //implementation here 
  }

//To register 
  val GiveNumVal = spark.sqlContext.udf.register("functionName", giveNumVal)
输出:

+---+---+---+
|x  |y  |z  |
+---+---+---+
|1  |10 |1  |
|2  |30 |3  |
|3  |50 |4  |
|4  |24 |2  |
|5  |36 |3  |
|6  |45 |4  |
+---+---+---+
注意:您不需要
返回
语句和


希望这有帮助

您应该在
GiveNumVal
函数中的
内置函数时使用
,因为if-else条件在列上不起作用

import org.apache.spark.sql.functions._
def  GiveNumVal(col: Column) = {
  when(col >= 0 && col < 15, 1).otherwise(
    when(col >= 15 && col < 30, 2).otherwise(
      when(col >= 30 && col < 45, 3).otherwise(
        when(col >= 45 && col <= 59, 4).otherwise(0)
      )
    )
  )
}
val new_df = df.withColumn("z", GiveNumVal($"y"))
new_df.show(false)
GiveNumVal
函数返回一个
,而不是
整数


我希望答案是有帮助的

您正在检查
列的值,您应该检查
列的值。除此之外,您创建的只是一个Scala函数,不能用于数据帧。
+---+---+---+
|x  |y  |z  |
+---+---+---+
|1  |10 |1  |
|2  |30 |3  |
|3  |50 |4  |
|4  |24 |2  |
|5  |36 |3  |
|6  |45 |4  |
+---+---+---+
import org.apache.spark.sql.functions._
def  GiveNumVal(col: Column) = {
  when(col >= 0 && col < 15, 1).otherwise(
    when(col >= 15 && col < 30, 2).otherwise(
      when(col >= 30 && col < 45, 3).otherwise(
        when(col >= 45 && col <= 59, 4).otherwise(0)
      )
    )
  )
}
val new_df = df.withColumn("z", GiveNumVal($"y"))
new_df.show(false)
+---+---+---+
|x  |y  |z  |
+---+---+---+
|1  |10 |1  |
|2  |30 |3  |
|3  |50 |4  |
|4  |24 |2  |
|5  |36 |3  |
|6  |45 |4  |
+---+---+---+