当新列丢失时,如何根据名称将新列添加到 DataFrame 中?

2024-01-10

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

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

当选择列时,数据框仅出现旧列,而不会出现新列。


它更多地是关于如何在 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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当新列丢失时,如何根据名称将新列添加到 DataFrame 中? 的相关文章

随机推荐