Pyspark: come dividere la colonna separata da pipe in più righe? [duplicare]

Aug 18 2020

Ho un dataframe che contiene quanto segue:

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

Vorrei ottenere un secondo dataframe (dal primo), che contenga quanto segue:

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

Come possiamo farlo usando pyspark?

Risposte

1 Shu Aug 18 2020 at 08:41

Use splitfunction restituirà una funzione arraythen explodesull'array.

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