Group by a Key
Part of the Fundamentals section of Coddy's PySpark journey. Lesson 11 of 18.
groupBy forms a group for each distinct key. Follow it with agg to compute one summary row per group. The grouping column is retained in the result.
visits.groupBy("city").agg(F.count("*").alias("visits"))The example counts visits for each city. Grouped rows have no guaranteed order. Grouping an empty table produces no groups and therefore no result rows. Grouping is different from a global aggregation, which still has one summary row.
Challenge
EasySum amount separately for each team. Return team, total. Teams and amounts are non-null; preserve every team, including a team whose total is zero.
Write transform(df) and return a Spark DataFrame. The checker supplies df with schema team string, amount int. The session and F (PySpark functions) are already available. Do not print; the checker displays the returned rows. Return columns in this order: team, total.
Try it yourself
def transform(df):
return df
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
3Summaries and Joins
Aggregate a TableGroup by a KeyJoin Two TablesQuery with Spark SQLRecap: Team TotalsPractice on your own: Online Python compiler