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

时间:2017-07-14 17:07:49

标签: python apache-spark pyspark apache-spark-sql pyspark-sql

我有这个PySpark数据帧

+-----------+--------------------+
|uuid       |   test_123         |    
+-----------+--------------------+
|      1    |[test, test2, test3]|
|      2    |[test4, test, test6]|
|      3    |[test6, test9, t55o]|

我希望将列test_123转换为:

+-----------+--------------------+
|uuid       |   test_123         |    
+-----------+--------------------+
|      1    |"test,test2,test3"  |
|      2    |"test4,test,test6"  |
|      3    |"test6,test9,t55o"  |

所以从列表到字符串。

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

3 个答案:

答案 0 :(得分:10)

虽然您可以使用UserDefinedFunction,但非常低效。相反,最好使用concat_ws函数:

from pyspark.sql.functions import concat_ws

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

答案 1 :(得分:7)

您可以创建加入数组/列表udf,然后将其应用于 test 列:

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|
+----+----------------+

初始数据框是从:

创建的
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]|
+----+--------------------+

答案 2 :(得分:0)

从 2.4.0 版开始,您可以使用 array_joinSpark docs


from pyspark.sql.functions import array_join

df.withColumn("test_123", array_join("test_123", ",")).show()