Pyspark:如何将管道分隔的列拆分为多行?

Pyspark : How to split pipe-separated column into multiple rows?

我有一个包含以下内容的数据框:

movieId / movieName / genre
1         example1    action|thriller|romance
2         example2    fantastic|action

我想获得第二个数据框(来自第一个数据框),其中包含以下内容:

movieId / movieName / genre
1         example1    action
1         example1    thriller
1         example1    romance
2         example2    fantastic
2         example2    action

我们如何使用 pyspark 做到这一点?

使用 split 函数将 return 一个 array 然后 explode 数组上的函数。

Example:

df.show(10,False)
#+-------+---------+-----------------------+
#|movieid|moviename|genre                  |
#+-------+---------+-----------------------+
#|1      |example1 |action|thriller|romance|
#+-------+---------+-----------------------+

from pyspark.sql.functions import *

df.withColumnRenamed("genre","genre1").\
withColumn("genre",explode(split(col("genre1"),'\|'))).\
drop("genre1").\
show()
#+-------+---------+--------+
#|movieid|moviename|   genre|
#+-------+---------+--------+
#|      1| example1|  action|
#|      1| example1|thriller|
#|      1| example1| romance|
#+-------+---------+--------+