Liz*_*zou 21 python pyspark spark-dataframe pyspark-sql
我每年使用以下代码来聚集学生.目的是了解每年的学生总数.
from pyspark.sql.functions import col
import pyspark.sql.functions as fn
gr = Df2.groupby(['Year'])
df_grouped =
gr.agg(fn.count(col('Student_ID')).alias('total_student_by_year'))
Run Code Online (Sandbox Code Playgroud)
结果是:
[学生按年份] [1]
我发现有这么多ID重复的问题所以结果是错误的和巨大的.
我希望按年份对学生进行聚集,按年计算学生总数,并将ID重复计算.
我希望这个问题很清楚.我是新成员谢谢
ash*_*ids 45
使用countDistinct函数
from pyspark.sql.functions import countDistinct
x = [("2001","id1"),("2002","id1"),("2002","id1"),("2001","id1"),("2001","id2"),("2001","id2"),("2002","id2")]
y = spark.createDataFrame(x,["year","id"])
gr = y.groupBy("year").agg(countDistinct("id"))
gr.show()
Run Code Online (Sandbox Code Playgroud)
产量
+----+------------------+
|year|count(DISTINCT id)|
+----+------------------+
|2002| 2|
|2001| 2|
+----+------------------+
Run Code Online (Sandbox Code Playgroud)