【问题标题】:How to add new columns to DataFrame given their names when they are missing?如何在缺少名称时将新列添加到 DataFrame?
【发布时间】:2017-09-14 01:50:34
【问题描述】:

我想将选定的列添加到尚不可用的 DataFrame。

val columns=List("Col1","Col2","Col3") 
for(i<-columns) 
 if(!df.schema.fieldNames.contains(i)==true)
 df.withColumn(i,lit(0))

When select column the data frame only old column are coming, new columns are not coming.

【问题讨论】:

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


    【解决方案1】:

    它更多地是关于如何在 Scala 中而不是 Spark,并且是 foldLeft 的绝佳案例(我最喜欢的!)

    // start with an empty DataFrame, but could be anything
    val df = spark.emptyDataFrame
    val columns = Seq("Col1", "Col2", "Col3")
    val columnsAdded = columns.foldLeft(df) { case (d, c) =>
      if (d.columns.contains(c)) {
        // column exists; skip it
        d
      } else {
        // column is not available so add it
        d.withColumn(c, lit(0))
      }
    }
    
    scala> columnsAdded.printSchema
    root
     |-- Col1: integer (nullable = false)
     |-- Col2: integer (nullable = false)
     |-- Col3: integer (nullable = false)
    

    【讨论】:

      【解决方案2】:

      你也可以将列表达式放在一个序列中,并使用星号展开:

      val df = spark.range(10)
      
      // Filter out names
      val names = Seq("col1", "col2", "col3").filterNot(df.schema.fieldNames.contains)
      
      // Create columns
      val cols = names.map(lit(0).as(_))
      
      // Append the new columns to the existing columns.
      df.select($"*" +: cols: _*)
      

      【讨论】:

        猜你喜欢
        • 2021-05-12
        • 1970-01-01
        • 1970-01-01
        • 2015-10-15
        • 1970-01-01
        • 1970-01-01
        • 2022-11-16
        • 2018-10-15
        • 1970-01-01
        相关资源
        最近更新 更多