我有一个看起来像这样的数据框:
Genres | Year | Number_Movies
Drama |2015 | 705
Romance|2015 | 203
Comedy |2015 | 586
Drama |2014 | 605
Romance|2014 | 293
Comedy |2014 | 786
我想按年份返回电影数量最多的性别:
Genres | Year | Number_Movies
Drama |2015 | 705
Comedy |2014 | 786
请尽可能提供帮助。非常感谢。
答案 0 :(得分:1)
以下是可以解决此问题的几种方法-
df = spark.createDataFrame([('Drama',2015,705),('Romance',2015,203),('Comedy',2015,586),('Drama',2014,605),('Romance',2014,293),('Comedy ',2014,786)],['Genres','Year','Number_Movies'])
第一个选项:使用窗口函数定义等级(按-年划分和按-Number_Movies desc排序)。最高的Number_Movies每年将获得等级“ 1”。
from pyspark.sql.window import Window
from pyspark.sql.functions import row_number,desc
w = Window.partitionBy("Year").orderBy(desc("Number_Movies"))
rank = row_number().over(w).alias('rank')
df.withColumn("rank", rank)\
.where("rank=1")\
.drop("rank")\
.show()
#+-------+----+-------------+
#| Genres|Year|Number_Movies|
#+-------+----+-------------+
#|Comedy |2014| 786|
#| Drama|2015| 705|
#+-------+----+-------------+
第二个选择::每年获取最多Number_Movies影片,并与数据框自加入以获得流派。
from pyspark.sql.functions import max,col
joining_condition = [col('a.Year') == col('b.Year'), col('a.max_Number_Movies') == col('b.Number_Movies')]
df.groupBy("Year").\
agg(max("Number_Movies").alias("max_Number_Movies")).alias("a").\
join(df.alias("b"), joining_condition).\
selectExpr("b.Genres","b.Year","b.Number_Movies").\
show()
#+-------+----+-------------+
#| Genres|Year|Number_Movies|
#+-------+----+-------------+
#|Comedy |2014| 786|
#| Drama|2015| 705|
#+-------+----+-------------+