Pyspark: จะแยกคอลัมน์ที่คั่นด้วยท่อออกเป็นหลายแถวได้อย่างไร? [ซ้ำ]
Aug 18 2020
ฉันมีดาต้าเฟรมที่มีสิ่งต่อไปนี้:
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 Shu Aug 18 2020 at 08:41
split
ฟังก์ชันUse จะส่งคืนฟังก์ชัน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|
#+-------+---------+--------+