在数据框中将字符串转换为双精度

ulr*_*ich 3 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|
+-------------+
Run Code Online (Sandbox Code Playgroud)

我怎样才能将它转换回双倍?

我试过投射到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|
+----+
Run Code Online (Sandbox Code Playgroud)

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

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

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

val testDouble = dfConcat
.withColumn("test",      toDbl(dfConcat("test")))              
.select("test")
Run Code Online (Sandbox Code Playgroud)

zer*_*323 5

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

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

df.select(array($"k", $"v").as("test"))
Run Code Online (Sandbox Code Playgroud)

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

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

dfConcat.select(split($"test", ",").cast(ArrayType(DoubleType)))
Run Code Online (Sandbox Code Playgroud)