使用spark数据帧计算每部电影的标签频率



我有一个数据帧,由两列movieid和应用于该电影的标签组成,格式如下-

movieid   tag                                                                                     
1         animation
1         pixar 
1         animation 
2         comedy                                                                            

我想为每个电影id计算每个标签被应用的次数,还想计算应用到每个电影的标签总数。我是个新手。

这是在PySpark中,如下所示:

创建df:

 sqlContext = SQLContext(sc)
 data = [(1,'animation'),(1,'pixar'),(1,'animation'),(2,'comedy')]
 RDD = sc.parallelize(data)
 orders_df = sqlContext.createDataFrame(RDD,["movieid","tag"])
 orders_df.show()
 +-------+---------+
 |movieid|      tag|
 +-------+---------+
 |      1|animation|
 |      1|    pixar|
 |      1|animation|
 |      2|   comedy|
 +-------+---------+

计算:

 orders_df.groupBy(['movieid','tag']).count().show() #count for each movie id how many times each tags are applied
 +-------+---------+-----+
 |movieid|      tag|count|
 +-------+---------+-----+
 |      1|    pixar|    1|
 |      1|animation|    2|
 |      2|   comedy|    1|
 +-------+---------+-----+
 orders_df.groupBy(['movieid']).count().show() #number of tags applied to each movie
 +-------+-----+
 |movieid|count|
 +-------+-----+
 |      1|    3|
 |      2|    1|
 +-------+-----+

最新更新