将PySpark dataframe列从列表转换为字符串

Dko*_*ova 11 python apache-spark apache-spark-sql pyspark pyspark-sql

我有这个PySpark数据帧

+-----------+--------------------+
|uuid       |   test_123         |    
+-----------+--------------------+
|      1    |[test, test2, test3]|
|      2    |[test4, test, test6]|
|      3    |[test6, test9, t55o]|
Run Code Online (Sandbox Code Playgroud)

我想将列转换为test_123这样:

+-----------+--------------------+
|uuid       |   test_123         |    
+-----------+--------------------+
|      1    |"test,test2,test3"  |
|      2    |"test4,test,test6"  |
|      3    |"test6,test9,t55o"  |
Run Code Online (Sandbox Code Playgroud)

所以从列表到字符串.

我怎么能用PySpark做到这一点?

use*_*411 16

虽然你可以使用UserDefinedFunction它是非常低效的.相反,最好使用concat_ws功能:

from pyspark.sql.functions import concat_ws

df.withColumn("test_123", concat_ws(",", "test_123")).show()
Run Code Online (Sandbox Code Playgroud)
+----+----------------+
|uuid|        test_123|
+----+----------------+
|   1|test,test2,test3|
|   2|test4,test,test6|
|   3|test6,test9,t55o|
+----+----------------+
Run Code Online (Sandbox Code Playgroud)


Psi*_*dom 11

您可以创建一个udf连接数组/列表,然后将其应用于测试列:

from pyspark.sql.functions import udf, col

join_udf = udf(lambda x: ",".join(x))
df.withColumn("test_123", join_udf(col("test_123"))).show()

+----+----------------+
|uuid|        test_123|
+----+----------------+
|   1|test,test2,test3|
|   2|test4,test,test6|
|   3|test6,test9,t55o|
+----+----------------+
Run Code Online (Sandbox Code Playgroud)

初始数据框是从以下位置创建的:

from pyspark.sql.types import StructType, StructField
schema = StructType([StructField("uuid",IntegerType(),True),StructField("test_123",ArrayType(StringType(),True),True)])
rdd = sc.parallelize([[1, ["test","test2","test3"]], [2, ["test4","test","test6"]],[3,["test6","test9","t55o"]]])
df = spark.createDataFrame(rdd, schema)

df.show()
+----+--------------------+
|uuid|            test_123|
+----+--------------------+
|   1|[test, test2, test3]|
|   2|[test4, test, test6]|
|   3|[test6, test9, t55o]|
+----+--------------------+
Run Code Online (Sandbox Code Playgroud)