如何在 DataFrame 的新列中正确格式化字符串?

How to properly format the string in a new column of DataFrame?

我有一个包含两列 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)

如评论中所述,您可以多次使用 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)

这是一个老问题,但我把我的答案放在这里是为了其他人。您可以使用 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)|
+----+----+--------------------------------------------------+