I need some help with a DataFrame.
I have a math form in a column and I want to apply the form to the DataFrame, saving the result in other column.
DF:
val metricsRows = List(
Row.fromSeq(Seq("Math1","double_1 + double_2",12.0,12.0,null)),
Row.fromSeq(Seq("Math2","double_2 - double_1",1000.0,10.0,null)),
Row.fromSeq(Seq("Math3","double_1 + double_1",12.02,19.02,null)),
)
val metricsSchema = StructType(Seq(
StructField("Id", StringType, nullable = false),
StructField("form", StringType, nullable = false),
StructField("double_1", DoubleType, nullable = false),
StructField("double_2", DoubleType, nullable = false),
StructField("double_result", DoubleType, nullable = false))
)
val metricsDF = sqlc.createDataFrame(sc.parallelize(metricsRows), metricsSchema)
The result that I like to have:
+-------+---------------------+----------+----------+--------------+
|Id |form |double_1 |double_2 |double_result |
+-------+---------------------+----------+----------+--------------+
|Math1 |double_1 + double_2 |12.0 |12.0 |24.4 |
|Math2 |double_2 - double_1 |1000.0 |10.0 |-990.0 |
|Math3 |double_1 + double_1 |12.02 |19.02 |24.04 |
+-------+---------------------+----------+----------+--------------+
But I don't know how to get the form column values and interpret as column names.
I tried this:
val resultDF= metricsDF.withColumn("double_result",expr(col("form").toString()))
And the output is:
+-------+---------------------+----------+----------+---------------------+
|Id |form |double_1 |double_2 |double_result |
+-------+---------------------+----------+----------+---------------------+
|Math1 |double_1 + double_2 |12.0 |12.0 |double_1 + double_2 |
|Math2 |double_2 - double_1 |1000.0 |10.0 |double_2 - double_1 |
|Math3 |double_1 + double_1 |12.02 |19.02 |double_1 + double_1 |
+-------+---------------------+----------+----------+---------------------+
How can I do this? I tried other options with no results.
Thank you!