在数据帧中将字符串转换为double

时间:2016-03-13 14:20:39

标签: apache-spark apache-spark-sql

我使用concat构建了一个生成字符串的数据框。

import sqlContext.implicits._

val df = sc.parallelize(Seq((1.0, 2.0), (3.0, 4.0))).toDF("k", "v")
df.registerTempTable("df")

val dfConcat = df.select(concat($"k", lit(","), $"v").as("test"))

dfConcat: org.apache.spark.sql.DataFrame = [test: string]

+-------------+
|         test|
+-------------+
|      1.0,2.0|
|      3.0,4.0|
+-------------+

如何将其转换回双倍?

我已尝试投放到DoubleType,但我得null

import org.apache.spark.sql.types._
 intterim.features.cast(IntegerType))

val testDouble = dfConcat.select( dfConcat("test").cast(DoubleType).as("test"))

+----+
|test|
+----+
|null|
|null|
+----+

udf在运行时返回数字格式异常

import org.apache.spark.sql.functions._

val toDbl    = udf[Double, String]( _.toDouble)

val testDouble = dfConcat
.withColumn("test",      toDbl(dfConcat("test")))              
.select("test")

1 个答案:

答案 0 :(得分:4)

您无法将其转换为double,因为它不是有效的双重表示。如果你想要一个数组,只需使用array函数:

import org.apache.spark.sql.functions.array

df.select(array($"k", $"v").as("test"))

您也可以尝试拆分和转换,但它远非最佳:

import org.apache.spark.sql.types.{ArrayType, DoubleType}
import org.apache.spark.sql.functions.split

dfConcat.select(split($"test", ",").cast(ArrayType(DoubleType)))