Start learning free

LESSON 18 OF 165 · MACHINE LEARNING: PANDAS

Group and Summarize

Practice

Which city spends the most? One average over all 300 customers can't tell you: you need one average per city. groupby gets it in three moves. It splits the rows into groups, one per city; it applies a summary, like the mean of spent, to each group on its own; and it combines the results into one table. If you know SQL, it is GROUP BY.

df.groupby("newsletter") gives back the groups, with nothing computed yet. ["visits"] picks one column inside every group, and .mean() gives back a Series: one row per group, with the group names as its index (in A to Z order) and the averages as its values. Printed with .to_string(), it shows the index name on top, then one line per group.

avg_visits = df.groupby("newsletter")["visits"].mean()
print(avg_visits.round(1).to_string())

Groups match the exact text, so the starting code cleans the cities first: " cluj " and "Cluj" become one city, and the blank cities become "Unknown" (groupby leaves rows with a blank key out). To see the biggest spenders first, sort the result by its values: sort_values(ascending=False) gives back the same Series with the highest number on top, and .head(3) gives back its first 3 rows.

Your finished script prints the average spend of every city, then the top 3:

city
Berlin     192.27
Cluj       188.46
Lyon       188.23
Madrid     183.41
Porto      191.48
Rome       199.12
Unknown    173.89
city
Rome      199.12
Berlin    192.27
Porto     191.48

Your task: the file is read and the cities are cleaned for you. Below the cleaning line, group the customers by city, take the mean of spent into avg_spent and print it rounded to 2 decimals. Then sort avg_spent from the highest average to the lowest into top, and print the first 3 rows of top, rounded the same way.


Assignment
Follow the Coding Tutorial to group the customers by city, print the average spend of each city, then sort the averages and print the top 3.


Hint
The chain reads left to right: groupby("city"), then the column in square brackets, then .mean(). A Series has sort_values too; ascending=False puts the biggest first. Print with .round(2).to_string().


STEP 1 OF 4
    Ctrl + Enter to check