sks*_*sks 5 scala dataframe apache-spark 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))
Run Code Online (Sandbox Code Playgroud)
当选择列时,只有旧列的数据框即将到来,新列不会到来.
它更多的是关于如何在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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1244 次 |
| 最近记录: |