Start learning free

LESSON 27 OF 165 · MACHINE LEARNING: ANALYSIS PROJECTS

Cohorts: Customers by Join Month

Practice

A cohort is a group of customers who started at the same time. Grouping customers by the month they joined shows whether newer customers behave differently from older ones. Compare with care: someone who joined in January has had months more to shop than someone who joined in October, so older cohorts get a head start in every total.

read_csv reads joined as text like "2026-03-14". pd.to_datetime(column) gives back the column as real dates, and .dt.month gives back the month of each date as a number, 1 for January:

dates = pd.to_datetime(pd.Series(["2026-03-14", "2026-07-02"]))
print(dates.dt.month.tolist())   # [3, 7]

To make several summaries per group at once, call .agg with named summaries: each one is new_name=(column, "count") or new_name=(column, "mean"). It gives back a table with one row per group and one column per name. On orders.csv, for example:

per_category = orders.groupby("category").agg(
    lines=("order_id", "count"),
    avg_quantity=("quantity", "mean"),
)

The group values become the table's row labels, its index: table.index.min() and table.index.max() give back the smallest and the largest label, and table.loc[row, "column"] gives back one cell. Your script must print:

        customers  avg_spent  again
cohort                             
1              27    140.185  0.556
2              29    145.138  0.483
3              33    185.788  0.545
4              32    199.031  0.500
5              28    163.107  0.464
6              23    217.217  0.609
7              27    206.593  0.704
8              36    198.194  0.611
9              36    207.444  0.750
10             29    232.414  0.724
Month 10 joiners spent 232.4 on average, month 1 joiners 140.2, though they had 9 more months to shop.

Your task: turn joined into dates, give every customer a cohort (the month they joined), build a table per cohort with the number of customers, their average spent and the share who bought again, print it rounded to 3 decimals, and end with a sentence comparing the newest and the oldest cohort, their average spent rounded to 1 decimal.


Assignment
Follow the Coding Tutorial to group the shop's customers by join month and compare the first and the last cohort.


Hint
Each line inside agg( is one summary and ends with a comma. The row labels of cohorts are month numbers, so newest - oldest is the number of months between the two cohorts. Inside the f-string, write column names with single quotes: 'avg_spent'.


STEP 1 OF 10
    Ctrl + Enter to check