如何将新列添加到DataFrame,并在缺少时给出它们的名称?

时间:2017-04-18 09:33:36

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

我想将所选列添加到尚未提供的DataFrame中。

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

当选择列时,只有旧列的数据框即将到来,新列不会到来。

2 个答案:

答案 0 :(得分:8)

它更多是关于如何在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)

答案 1 :(得分: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: _*)