【问题标题】:How to properly format the string in a new column of DataFrame?如何在 DataFrame 的新列中正确格式化字符串?
【发布时间】:2022-04-03 22:09:09
【问题描述】:

我有一个包含两列 col1col2 的 DataFrame(Spark 2.2.0 和 Scala 2.11)。我需要按以下格式创建一个新列:

=path("http://mywebsite.com/photo/AAA_BBB.jpg", 1)

其中AAAcol1 的值,BBB 是给定行的col2 的值。

问题是我不知道如何正确处理"。我试过这个:

df = df.withColumn($"url",=path("http://mywebsite.com/photo/"+col("col1") + "_"+col("col2")+".jpg", 1))"

更新:

现在可以编译了,但是列值没有插入到字符串中。我看到的不是列值,而是 col1col2 文本。

df = df.withColumn("url_rec",lit("=path('http://mywebsite.com/photo/"+col("col1")+"_"+col("col1")+".jpg', 1)"))

我明白了:

=path('http://mywebsite.com/photo/col1_col1.jpg', 1)

【问题讨论】:

  • 你试过在中间转义引号吗?比如 "=path(\"mywebsite.com/photo"
  • @Fabich:请查看我的更新。我能够编译代码。但是当我运行它时,我得到的字符串没有插入这些字符串中的列的值。
  • 如果你想为每一行更改它,你将不得不一个接一个地使用多个concat
  • @philantrovert:好的,我明白了。现在它起作用了。谢谢。您能否将您的建议放入答案中?

标签: scala apache-spark spark-dataframe


【解决方案1】:

如 cmets 所述,您可以多次使用 concat,例如:

d.show
+---+---+
|  a|  b|
+---+---+
|AAA|BBB|
+---+---+

d.withColumn("URL" , 
   concat(
       concat(
           concat(
               concat(lit("""=path("http://mywebsite.com/photo/""" ), $"a") ,
               lit("_") ) , $"b" 
           ) 
           , lit(""".jpg", 1) """) 
         ).as[String].first

// String = "=path("http://mywebsite.com/photo/AAA_BBB.jpg", 1) "

或者您可以映射数据框以附加一个新列(这比 concat 方法更干净)

import org.apache.spark.sql.Row
import org.apache.spark.sql.types._

val urlRdd = d.map{ x => 
     Row.fromSeq(x.toSeq ++ Seq(s"""=path("http://mywebsite.com/photo/${x.getAs[String]("a")}_${x.getAs[String]("b")}.jpg", 1)""")) 
    }

val newDF = sqlContext.createDataFrame(urlRdd, d.schema.add("url", StringType) )

newDF.map(_.getAs[String]("url")).first
// String = =path("http://mywebsite.com/photo/AAA_BBB.jpg", 1)

【讨论】:

    【解决方案2】:

    这是一个老问题,但我把我的答案放在这里给其他人。你可以使用format_string函数

    scala> df1.show()
    +----+----+
    |col1|col2|
    +----+----+
    | AAA| BBB|
    +----+----+
    
    scala> df1.withColumn(
                "URL",
                format_string(
                    """=path("http://mywebsite.com/photo/%s_%s.jpg", 1)""", 
                    col("col1"), 
                    col("col2")
                )
            ).show(truncate = false)
    
    +----+----+--------------------------------------------------+
    |col1|col2|URL                                               |
    +----+----+--------------------------------------------------+
    |AAA |BBB |=path("http://mywebsite.com/photo/AAA_BBB.jpg", 1)|
    +----+----+--------------------------------------------------+
    

    【讨论】:

      猜你喜欢
      • 2014-10-12
      • 2017-09-25
      • 2014-09-22
      • 2020-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-24
      • 1970-01-01
      相关资源
      最近更新 更多