给定表1,其中一列为"x",类型为String.我想创建表2,其中列为"y",它是"x"中给出的日期字符串的整数表示形式.
必不可少的是将null值保留在"y"列中.
表1(数据帧df1):
+----------+
| x|
+----------+
|2015-09-12|
|2015-09-13|
| null|
| null|
+----------+
root
|-- x: string (nullable = true)
Run Code Online (Sandbox Code Playgroud)
表2(数据帧df2):
+----------+--------+
| x| y|
+----------+--------+
| null| null|
| null| null|
|2015-09-12|20150912|
|2015-09-13|20150913|
+----------+--------+
root
|-- x: string (nullable = true)
|-- y: integer (nullable = true)
Run Code Online (Sandbox Code Playgroud)
用于将列"x"中的值转换为列"y"的用户定义函数(udf)为:
val extractDateAsInt = udf[Int, String] (
(d:String) => d.substring(0, 10)
.filterNot( "-".toSet)
.toInt )
Run Code Online (Sandbox Code Playgroud)
并且工作,处理空值是不可能的.
尽管如此,我可以做类似的事情
val extractDateAsIntWithNull = udf[Int, String] (
(d:String) =>
if (d != …Run Code Online (Sandbox Code Playgroud) scala nullable user-defined-functions apache-spark apache-spark-sql
我想向我的Spark数据帧添加一个具有随机生成的ID的列。为此,我使用UDF调用UUID的随机UUID方法,如下所示:
def getRandomId(s:String) : String = {
UUID.randomUUID().toString()
}
val idUdf = udf(getRandomId(_:String))
val newDf = myDf.withColumn("id", idUdf($"colName"))
Run Code Online (Sandbox Code Playgroud)
显然,我的getRandomId函数不需要输入参数。但是,我不知道如何创建不接受列作为输入的UDF。在Spark中有可能吗?
我正在使用Spark 1.5