如何将带有以下结构的RDD转换为scala
中的dataFrame org.apache.spark.rdd.RDD[(Long, org.apache.spark.mllib.linalg.Vector)] = MapPartitionsRDD[42]
这里的每一行都包含索引Long
和vector org.apache.spark.mllib.linalg.Vector
。
我想将org.apache.spark.mllib.linalg.Vector
的每个组件放在一排DataFrame中的单独列中。
以下示例有效。在这里,我假设向量大小为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|
+---+---+---+---+---+---+---+---+---+---+----+