将RDD转换为Dataframe Spark

时间:2017-02-26 00:05:20

标签: scala apache-spark apache-spark-sql spark-dataframe

如何将具有以下结构的RDD转换为scala中的数据框

org.apache.spark.rdd.RDD[(Long, org.apache.spark.mllib.linalg.Vector)] = MapPartitionsRDD[42]

此处每行RDD包含一个索引Long和一个向量org.apache.spark.mllib.linalg.Vector

我希望将org.apache.spark.mllib.linalg.Vector的每个组件放在一行数据框的单独列中。

1 个答案:

答案 0 :(得分:1)

以下示例有效。为简洁起见,我假设矢量大小为10.您应该能够将其缩放到1000

import org.apache.spark.mllib.linalg.Vectors
val rdd = sc.parallelize(Seq((1L,Vectors.dense((1 to 10).map(_ * 1.0).toArray))))
val df = rdd.map({case (a,b) => (a,b.toArray) }).toDF("c1", "c2")
df.select(($"c1" +: (0 to 9).map(idx => $"c2"(idx) as "c" + (idx + 2)):_*)).show()  
+---+---+---+---+---+---+---+---+---+---+----+
| c1| c2| c3| c4| c5| c6| c7| c8| c9|c10| c11|
+---+---+---+---+---+---+---+---+---+---+----+
|  1|1.0|2.0|3.0|4.0|5.0|6.0|7.0|8.0|9.0|10.0|
+---+---+---+---+---+---+---+---+---+---+----+