加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 18:19:13 所属栏目:安全 来源:网络整理
导读:我想将选定的列添加到尚未提供的DataFrame中. val columns=List("Col1","Col2","Col3") for(i-columns) if(!df.schema.fieldNames.contains(i)==true) df.withColumn(i,lit(0)) 当选择列时,只有旧列的数据框即将到来,新列不会到来. 解决方法 它更多的是关于
我想将选定的列添加到尚未提供的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","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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读