Start learning free

LESSON 19 OF 165 · MACHINE LEARNING: PANDAS

Several Summaries at Once in Python

Practice

In the last lesson, groupby gave you one summary per group, like the average spend of each city. Often you want several numbers for each group side by side: how many customers it has, how much they spend on average, how many came back. agg() does that in one call. It gives back a table with one row per group and one column per summary.

Inside agg( you write one named summary per line: new_name=(column, function). The name on the left becomes a column of the result; the pair on the right says which column to read and what to work out from it, like "count", "mean", "sum" or "max". Here it is on the order lines, grouped by category:

orders = pd.read_csv("orders.csv")
by_category = orders.groupby("category").agg(
    lines=("order_id", "count"),
    items=("quantity", "sum"),
)

by_category has one row per category, labeled with the category's name, and two columns: lines, how many order lines the category has, and items, how many items those lines add up to.

Two tips. The mean of a column of 1s and 0s is the share of 1s: bought_again is 1 for a customer who bought again and 0 for one who didn't, so its mean in a group is the share of that group that came back. And "count" counts only the values that aren't blank, so to count customers, count a column with no blanks, like customer_id.

Your program must print:

            customers  avg_spent  again
newsletter                             
no                167    175.066  0.485
yes               133    208.586  0.737

Your task: group the customers by newsletter and, in one agg call into summary, work out customers (the count of customer_id), avg_spent (the mean of spent) and again (the mean of bought_again). Print summary rounded to 3 decimals with .to_string().


Assignment
Follow the Coding Tutorial to build three named summaries per newsletter group in one agg call and print them.


Hint
Each named summary is one line, name=("column", "function"),, ending with a comma; the closing ) of agg sits on its own line below them. .round(3) rounds every column of the table at once and leaves the counts whole.


STEP 1 OF 5
    Ctrl + Enter to check

    Pd Agg in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free