用于DataType转换的udf函数,Scala

问题描述 投票:0回答:1

我有下一个DataFrame:

df.show()

+---------------+----+
|              x| num|
+---------------+----+
|[0.1, 0.2, 0.3]|   0|
|[0.3, 0.1, 0.1]|   1|
|[0.2, 0.1, 0.2]|   2|
+---------------+----+

此DataFrame遵循列的数据类型:

df.printSchema 
root
 |-- x: array (nullable = true)
 |    |-- element: double (containsNull = true)
 |-- num: long (nullable = true)

我尝试将当前DataFrame内的DoubleArray转换为FloatArray。我用udf的下一个语句来做:

val toFloat = udf[(val line: Seq[Double]) => line.map(_.toFloat)]
val test = df.withColumn("testX", toFloat(df("x")))

此代码目前无效。任何人都可以与我分享如何更改DataFrame的数组类型的解决方案吗?

我想要的是:

df.printSchema 
root
 |-- x: array (nullable = true)
 |    |-- element: float (containsNull = true)
 |-- num: long (nullable = true)

这个问题是基于问题How tho change the simple DataType in Spark SQL's DataFrame

scala apache-spark dataframe types
1个回答
1
投票

你的udf被错误地宣布了。你应该写如下:

val toFloat = udf((line: Seq[Double]) => line.map(_.toFloat))
© www.soinside.com 2019 - 2024. All rights reserved.