如何在Pyspark中根据特定条件添加列来丰富数据框?

3

I have a two different dataframes:

users:

+-------+---------+--------+
|user_id| movie_id|timestep|
+-------+---------+--------+
|   100 |   1000  |20200728|
|   101 |   1001  |20200727|
|   101 |   1002  |20200726|
+-------+---------+--------+

电影:

+--------+---------+--------------------------+
|movie_id|  title  |         genre            |
+--------+---------+--------------------------+
|   1000 |Toy Story|Adventure|Animation|Chil..|
|   1001 | Jumanji |Adventure|Children|Fantasy|
|   1002 | Iron Man|Action|Adventure|Sci-Fi   |
+--------+---------+--------------------------+

如何获得以下格式的数据框?这样我就可以通过相似度分数比较不同用户的口味偏好。
+-------+---------+---------+---------+--------+-----+
|user_id|  Action |Adventure|Animation|Children|Drama|
+-------+---------+---------+---------+---------+----+
|   100 |    0    |    1    |    1    |   1    |  0  |
|   101 |    1    |    2    |    0    |   1    |  0  |
+-------+---------+---------+---------+--------+-----+
1个回答

1
首先,你需要拆分你的“genre”列。
from pyspark.sql import functions as F

movies = movies.withColumn("genre", F.explode(F.split("genre", '\|')))
# use \ in front of | because split use regex

然后你加入
user_movie = users.join(movies, on='movie_id')

并且你会旋转

user_movie.groupBy("user_id").pivot("genre").agg(F.count("*")).fillna(0).show()

+-------+------+---------+---------+--------+-------+------+
|user_id|Action|Adventure|Animation|Children|Fantasy|Sci-Fi|
+-------+------+---------+---------+--------+-------+------+
|    100|     0|        1|        1|       1|      0|     0|
|    101|     1|        2|        0|       1|      1|     1|
+-------+------+---------+---------+--------+-------+------+

FYI:由于电影数据框中没有“戏剧”类型,因此未显示戏剧栏。但是,如果您拥有完整数据,则每种类型将有一列。

我建议使用F.explode(F.split("genre", '\|'))之后再进行连接。 - undefined

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