且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将字符串数组的列转换为字符串?

更新时间:2023-02-03 10:04:58

在 Spark 2.1+ 中,您可以使用以下方法对单个 Array 列中的值进行串联:

In Spark 2.1+ to do the concatenation of the values in a single Array column you can use the following:

  1. concat_ws 标准函数
  2. map 运算符
  3. 用户定义函数 (UDF)

concat_ws 标准函数

使用 concat_ws 函数.

concat_ws(sep: String, exprs: Column*): Column 使用给定的分隔符将多个输入字符串列连接成一个字符串列.

concat_ws(sep: String, exprs: Column*): Column Concatenates multiple input string columns together into a single string column, using the given separator.

val solution = words.withColumn("codes", concat_ws(" ", $"rate_plan_code"))
scala> solution.show
+--------------+-----------+
|         words|      codes|
+--------------+-----------+
|[hello, world]|hello world|
+--------------+-----------+

地图操作员

使用 map 操作符可以完全控制应该转型什么以及如何转型.

map Operator

Use map operator to have full control of what and how should be transformed.

ma​​p[U](func: (T) ⇒ U): Dataset[U] 返回一个新的 Dataset,其中包含将 func 应用于每个元素的结果.

map[U](func: (T) ⇒ U): Dataset[U] Returns a new Dataset that contains the result of applying func to each element.

scala> codes.show(false)
+---+---------------------------+
|id |rate_plan_code             |
+---+---------------------------+
|0  |[AAA, RACK, SMOBIX, SMOBPX]|
+---+---------------------------+

val codesAsSingleString = codes.as[(Long, Array[String])]
  .map { case (id, codes) => (id, codes.mkString(", ")) }
  .toDF("id", "codes")

scala> codesAsSingleString.show(false)
+---+-------------------------+
|id |codes                    |
+---+-------------------------+
|0  |AAA, RACK, SMOBIX, SMOBPX|
+---+-------------------------+

scala> codesAsSingleString.printSchema
root
 |-- id: long (nullable = false)
 |-- codes: string (nullable = true)