如何将RDD [List [Int]]转换为DataFrame?

时间:2017-07-10 09:20:12

标签: apache-spark apache-spark-sql

我有RDD[List[Int]],我不知道list[Int]的数量,我想将Rdd[List[Int]]转换为DataFrame,我该怎么做?

这是我的意见:

    val l1=Array(1,2,3,4)
    val l2=Array(1,2,3,4)
    val Lz=Seq(l1,l2)
    val rdd1=sc.parallelize(Lz,2) 

这是我期望的结果:

+---+---+---+---+
| _1| _2| _3| _4|
+---+---+---+---+
|  1|  2|  3|  4|
|  1|  2|  3|  4|
+---+---+---+---+

2 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

val l1=Array(1,2,3,4)
val l2=Array(1,2,3,4)
val Lz=Seq(l1,l2)
val df = sc.parallelize(Lz,2).map{
    case Array(val1, val2, val3, val4) => (val1, val2, val3, val4)
}.toDF

df.show
// +---+---+---+---+
// | _1| _2| _3| _4|
// +---+---+---+---+
// |  1|  2|  3|  4|
// |  1|  2|  3|  4|
// +---+---+---+---+

如果您有很多列,则需要采用不同的方式,但您需要知道数据的架构,否则您将无法执行以下操作:

val sch = df.schema // I just took the schema from the old df but you can add one programmatically 

val df2 = spark.createDataFrame(sc.parallelize(Lz,2).map{ Row.fromSeq(_) }, sch)

df2.show
// +---+---+---+---+
// | _1| _2| _3| _4|
// +---+---+---+---+
// |  1|  2|  3|  4|
// |  1|  2|  3|  4|
// +---+---+---+---+

除非您提供架构,否则除了拥有阵列列之外,您将无法做很多事情:

val df3 = sc.parallelize(Lz,2).toDF
// df3: org.apache.spark.sql.DataFrame = [value: array<int>]
df3.show
// +------------+
// |       value|
// +------------+
// |[1, 2, 3, 4]|
// |[1, 2, 3, 4]|
// +------------+
df3.printSchema
//root
// |-- value: array (nullable = true)
// |    |-- element: integer (containsNull = false)

答案 1 :(得分:1)

可能还有其他更好的功能性方法,但这也有效:

def getSchema(myArray : Array[Int]): StructType = {
    var schemaArray = scala.collection.mutable.ArrayBuffer[StructField]()
    for((el,idx) <- myArray.view.zipWithIndex){
        schemaArray += StructField("col"+idx , IntegerType, true)
    }
    StructType(schemaArray)
}

val l1=Array(1,2,3,4)
val l2=Array(1,2,3,4)
val Lz=Seq(l1,l2)
val rdd1=sc.parallelize(Lz,2).map(Row.fromSeq(_))
val schema = getSchema(l1) //Since both arrays will be of same type and size
val df = sqlContext.createDataFrame(rdd1, schema)
df.show()

+----+----+----+----+
|col0|col1|col2|col3|
+----+----+----+----+
|   1|   2|   3|   4|
|   1|   2|   3|   4|
+----+----+----+----+