Pyspark:パイプで区切られた列を複数の行に分割する方法は?[複製]
Aug 18 2020
次のものを含むデータフレームがあります。
movieId / movieName / genre
1 example1 action|thriller|romance
2 example2 fantastic|action
以下を含む2番目のデータフレーム(最初のデータフレームから)を取得したいと思います。
movieId / movieName / genre
1 example1 action
1 example1 thriller
1 example1 romance
2 example2 fantastic
2 example2 action
pysparkを使用してどのようにそれを行うことができますか?
回答
1 Shu Aug 18 2020 at 08:41
Usesplit
関数は、配列に対してarray
then関数を返し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|
#+-------+---------+--------+