gpt4 book ai didi

apache-spark - 如何在 Spark UDF 中编写多个 If 语句

转载 作者:行者123 更新时间:2023-12-04 05:14:59 26 4
gpt4 key购买 nike

我的要求是为年龄创建类别。我试图在 UDF 中编写多个 if 条件,但它采用 else 条件。我的代码如下。

我的数据

1,Ashok,23,asd
2,Joi,27,dfs
3,Sam,30,dft
4,Bob,37,dat

我的代码

val sqlContext = new org.apache.spark.sql.SQLContext(sc)
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types._
import org.apache.spark.sql._
import org.apache.spark.sql.SaveMode
import sqlContext.implicits._
val a = sc.textFile("file2.txt")
a.foreach(println)

val coder: (Int=>String)=(arg:Int)=>{if(arg>20&&arg<27) "20-27";if(arg>30&&arg<37) "30-37"; else "38+"}

val co = udf(coder)

val a2 = a1.select(col("Id"),col("Name"),col("Age"),col("Dpt"))

a2.withColumn("range",co(col("Age"))).show()

我得到的输出

1,Ashok,23,asd,38+
2,Joi,27,dfs,38+
3,Sam,30,dft,38+
4,Bob,37,dat,38+

对于显示 38+ 的每一行,请建议语法。

最佳答案

您应该使用 if - else if - else .

此外,您在检查 arg>27 && arg<30 时会跳过边界值。

您的 UDF 应如下所示:

val co = udf { (x: Int) => 
if (x >= 20 && x <=27) "20-27"
else if (x > 27 && x<=37 ) "28-37"
else "38+"
}

// co: org.apache.spark.sql.UserDefinedFunction = UserDefinedFunction(<function1>,StringType,List(IntegerType))

df.withColumn("range" , co($"age" ) ).show

// +---+-----+---+---+-----+
// | id| name|age|dpt|range|
// +---+-----+---+---+-----+
// | 1|Ashok| 23|asd|20-27|
// | 2| Joi| 27|dfs|28-37|
// | 3| Sam| 30|dft|28-37|
// | 4| Bob| 37|dat| 38+|
// +---+-----+---+---+-----+

关于apache-spark - 如何在 Spark UDF 中编写多个 If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46464125/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com