Reputation: 3587
I have built a dataframe using concat
which produces a string.
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|
+-------------+
How can I convert it back to double?
I have tried casting to DoubleType
but I get null
import org.apache.spark.sql.types._
intterim.features.cast(IntegerType))
val testDouble = dfConcat.select( dfConcat("test").cast(DoubleType).as("test"))
+----+
|test|
+----+
|null|
|null|
+----+
and udf
return number format exception at run time
import org.apache.spark.sql.functions._
val toDbl = udf[Double, String]( _.toDouble)
val testDouble = dfConcat
.withColumn("test", toDbl(dfConcat("test")))
.select("test")
Upvotes: 3
Views: 18879
Reputation: 330423
You cannot convert it to double because it is simply not a valid double representation. If you want an array just use array
function:
import org.apache.spark.sql.functions.array
df.select(array($"k", $"v").as("test"))
You can also try to split and convert but it is far from optimal:
import org.apache.spark.sql.types.{ArrayType, DoubleType}
import org.apache.spark.sql.functions.split
dfConcat.select(split($"test", ",").cast(ArrayType(DoubleType)))
Upvotes: 5