简体   繁体   English

需要使用scala删除spark数据框列名中的字符串“_value”

[英]Need to remove string "_value" in spark dataframe column names using scala

Have my dataframe as shown below.Here I have to remove the last occurrence of the string "_value" from all the column name of my dataframe.让我的数据框如下所示。这里我必须从我的数据框的所有列名中删除字符串“_value”的最后一次出现。

import spark.implicits._
import org.apache.spark.sql.functions._
val simpledata = Seq(("file1","name1","101"),
("file1","name1","101"),
("file1","name1","101"),
("file1","name1","101"),
("file1","name1","101"))
val df = simpledata.toDF("filename_value","name_value_value","serialNo_value")
df.show()

Output menu enter image description here If I use replaceAll: val renamedColumnsDf = df.columns.map(c => df(c).as(c.replaceAll('_value',""))) it removes all the _values but i need only to remove the string based on last occurance.输出菜单在此处输入图像描述如果我使用 replaceAll: val renamedColumnsDf = df.columns.map(c => df(c).as(c.replaceAll('_value',"")))它会删除所有 _values 但我只需要根据最后一次出现删除字符串。

Need help here to remove the string based on occurrence in column name.此处需要帮助以根据列名中的出现来删除字符串。

My output should be:我的输出应该是:

      +--------------+----------------+--------------+
      |filename      |name_value      |serialNo      |
      +--------------+----------------+--------------+
      |         file1|           name1|           101|
      |         file1|           name1|           101|
      |         file1|           name1|           101|
      |         file1|           name1|           101|
      |         file1|           name1|           101|
      +--------------+----------------+--------------+

If you wish to remove the _value substring only if it is the suffix of the column name, you can do the following:如果您希望仅在_value子字符串是列名的后缀时删除它,您可以执行以下操作:

  val simpleDf: DataFrame = simpledata.toDF("filename_value", "name_value_value", "serialNo_value")

  val suffix: String = "_value"
  val renamedDf: DataFrame = simpleDf.columns.foldLeft(simpleDf) { (df, c) =>
    if (c.endsWith(suffix)) df.withColumnRenamed(c, c.substring(0, c.length - suffix.length)) else df}
  renamedDf.show()

The output will be:输出将是:

+--------+----------+--------+
|filename|name_value|serialNo|
+--------+----------+--------+
|   file1|     name1|     101|
|   file1|     name1|     101|
|   file1|     name1|     101|
|   file1|     name1|     101|
|   file1|     name1|     101|
+--------+----------+--------+

Why bother complicated coding?为什么要麻烦复杂的编码? You can use pattern matching on the column name inside your map transformation:您可以在地图转换中的列名上使用模式匹配:

val newName = columnName match {
  case s"${something}_value" => something
  case other => other
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM