开发者社区> 问答> 正文

如何重命名scala数据框中的列标题

如何在scala数据帧上执行string.replace(“fromstr”,“tostr”)。据我所知,withColumnRenamed执行替换所有列而不仅仅是标题。

展开
收起
社区小助手 2018-12-12 15:11:43 1533 0
1 条回答
写回答
取消 提交回答
  • 社区小助手是spark中国社区的管理员,我会定期更新直播回顾等资料和文章干货,还整合了大家在钉群提出的有关spark的问题及回答。

    withColumnRenamed仅重命名列名称,数据保持不变。如果需要更改行上下文,可以使用以下方法之一:

    import sparkSession.implicits._
    import org.apache.spark.sql.functions._

    val inputDf = Seq("to_be", "misc").toDF("c1")
    val resultd1Df = inputDf
    .withColumn("c2", regexp_replace($"c1", "^to_be$", "not_to_be"))
    .select($"c2".as("c1"))
    resultd1Df.show()

    val resultd2Df = inputDf
    .withColumn("c2", when($"c1" === "to_be", "not_to_be").otherwise($"c1"))
    .select($"c2".as("c1"))
    resultd2Df.show()

    def replace(mapping: Map[String, String]) = udf(
    (from: String) => mapping.get(from).orElse(Some(from))
    )

    val resultd3Df = inputDf
    .withColumn("c2", replace(Map("to_be" -> "not_to_be"))($"c1"))
    .select($"c2".as("c1"))
    resultd3Df.show()
    输入数据帧:

    c1
    to_be
    misc

    结果数据框:

    c1
    not_to_be
    misc
    2019-07-17 23:20:13
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
相关产品:
问答排行榜
最热
最新

相关电子书

更多
Just Enough Scala for Spark 立即下载
JDK8新特性与生产-for“华东地区scala爱好者聚会” 立即下载
低代码开发师(初级)实战教程 立即下载