Pyspark:如何计算单个群组的平均和计数?

时间:2018-08-01 11:28:40

标签: group-by count pyspark average

我想计算平均值,并在Pyspark中按语句分组计算。我该怎么办?

df = spark.createDataFrame([(1, 'John', 1.79, 28,'M', 'Doctor'),
                        (2, 'Steve', 1.78, 45,'M', None),
                        (3, 'Emma', 1.75, None, None, None),
                        (4, 'Ashley',1.6, 33,'F', 'Analyst'),
                        (5, 'Olivia', 1.8, 54,'F', 'Teacher'),
                        (6, 'Hannah', 1.82, None, 'F', None),
                        (7, 'William', 1.7, 42,'M', 'Engineer'),
                        (None,None,None,None,None,None),
                        (8,'Ethan',1.55,38,'M','Doctor'),
                        (9,'Hannah',1.65,None,'F','Doctor')]
                       , ['Id', 'Name', 'Height', 'Age', 'Gender', 'Profession'])

#这仅显示avg,但我需要在其旁边计数。我该怎么办?

df.groupBy("Profession").agg({"Age":"avg"}).show()
df.show()

谢谢。

1 个答案:

答案 0 :(得分:6)

对于同一列:

from pyspark.sql import functions as F
df.groupBy("Profession").agg(F.mean('Age'), F.count('Age')).show()

如果您可以使用其他列:

df.groupBy("Profession").agg({'Age':'avg', 'Gender':'count'}).show()