Ali*_*ice 3 apache-spark apache-spark-sql
我的要求是为age创建类别.我正在尝试在UDF中编写多个if条件但是它正在使用其他条件.我的代码如下.
我的数据
1,Ashok,23,asd
2,Joi,27,dfs
3,Sam,30,dft
4,Bob,37,dat
Run Code Online (Sandbox Code Playgroud)
我的代码
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()
Run Code Online (Sandbox Code Playgroud)
输出我得到了
1,Ashok,23,asd,38+
2,Joi,27,dfs,38+
3,Sam,30,dft,38+
4,Bob,37,dat,38+
Run Code Online (Sandbox Code Playgroud)
对于每行显示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+|
// +---+-----+---+---+-----+
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4362 次 |
| 最近记录: |