Scala創建新的空DataFrame

Scala創建新的空DataFrame

前言

本文主要是對Scala中創建空DataFrame的方式進行介紹,以下將會列舉不同的代碼示例

實現

方式一:

	/**
     * 創建一個空的DataFrame,代表用戶
     * 有四列,分別代表ID、名字、年齡、生日
     */
    val colNames = Array("id", "name", "age", "birth")
    //爲了簡單起見,字段類型都爲String
    val schema = StructType(colNames.map(fieldName => StructField(fieldName, StringType, true)))
    //主要是利用了spark.sparkContext.emptyRDD
    val emptyDf = spark.createDataFrame(spark.sparkContext.emptyRDD[Row], schema)

    emptyDf.show

方式二:

	/**
     * 可以給每列指定相對應的類型
     */
    val schema1 = StructType(
      Seq(
        StructField("id", IntegerType, true),
        StructField("name", StringType, true),
        StructField("age", IntegerType, true),
        StructField("birth", StringType, true)))
    val emptyDf1 = spark.createDataFrame(spark.sparkContext.emptyRDD[Row], schema1)
    emptyDf1.show

方式三:

	//一種空的DataFrame,沒有任何行任何列
    spark.emptyDataFrame.show

參考博客

Spark創建空的DataFrame - 董可倫 - CSDN博客

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章