Pyspark:如何将以竖线分隔的列拆分为多行?

4

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

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实现呢?

1个回答

6
使用 split 函数将返回一个 array,然后在数组上使用 explode 函数。 示例:
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|
#+-------+---------+--------+

1
谢谢。这也可以运行。 df.withColumn("genre",explode(split(col("genre"),'\|'))).show() 你为什么要添加genre1列然后又删除它呢? - Codegator

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接