Find a course

Module 3: pandas: Working with TablesLesson 7 of 1215 min

Grouping and Aggregation

Summarize data with groupby using split-apply-combine, compute several statistics at once with agg, count categories, and build pivot tables.

Step 1 of 13Learn

Split, apply, combine

Most business questions are really grouping questions. Average rentals per station. Revenue per month. Number of customers per country. pandas answers them with groupby, following a pattern called split-apply-combine:

  1. Split the rows into groups by one or more key columns.
  2. Apply a function to each group, such as sum, mean or count.
  3. Combine the results into a new table.
df.groupby("station")["bikes_out"].mean()
# station
# Harbor    10.0
# Market     9.0
# Park      11.0

Read it as: "group the rows by station, take the bikes_out column, and average it in each group." The result is a Series indexed by station.

More examples:

df.groupby("station")["bikes_out"].sum()
df.groupby("station").size()                    # rows per group
df.groupby(["station", "hour"])["bikes_out"].mean()   # two keys
df.groupby("station", as_index=False)["bikes_out"].mean()  # keep station as a column

With two keys, the result has a MultiIndex (station, hour). .reset_index() turns index levels back into ordinary columns, which is usually easier for plotting or exporting.

Two details: rows whose key is missing (NaN) are dropped from groupby by default (dropna=False keeps them), and aggregation functions such as mean skip NaN values within each group.

Split, apply, combine: groupby mean of bikes out per stationSplitHarbor14Market9Harbor6Park11Market13Harbor10Apply mean()Harbor: 14, 6, 10 → 10Market: 9, 13 → 11Park: 11 → 11CombineHarbor10.0Market11.0Park11.0

Step 2 of 13Practice · Work it out

Rentals: Harbor 14, Market 9, Harbor 6, Park 11, Market 13, Harbor 10. What does df.groupby("station")["bikes_out"].mean() return for Harbor?

Step 3 of 13Practice · Code challenge · Python

Write group_mean(records, key, value) that returns a dictionary mapping each group (each distinct record[key]) to the mean of record[value] in that group, rounded to 2 decimal places. This is what df.groupby(key)[value].mean() computes.

Real Python, running in a sandbox in your browser.
  • group_mean([{"st": "Harbor", "b": 14}, {"st": "Market", "b": 9}, {"st": "Harbor", "b": 6}, {"st": "Park", "b": 11}, {"st": "Market", "b": 13}, {"st": "Harbor", "b": 10}], "st", "b")
  • group_mean([{"g": "x", "v": 1}, {"g": "x", "v": 2}], "g", "v")
  • group_mean([{"g": "a", "v": 1}, {"g": "a", "v": 1}, {"g": "a", "v": 2}], "g", "v")

Step 4 of 13Learn

Several statistics at once: agg

.agg() computes multiple summaries in one pass:

df.groupby("station")["bikes_out"].agg(["count", "mean", "max"])
#          count  mean  max
# Harbor       3  10.0   14
# Market       2  11.0   13
# Park         1  11.0   11

Named aggregation gives clean output column names and lets you aggregate different columns differently:

summary = df.groupby("station").agg(
    rentals=("bikes_out", "size"),
    avg_bikes=("bikes_out", "mean"),
    first_hour=("hour", "min"),
)

Common aggregation functions: count (non-missing values), size (all rows, including missing), sum, mean, median, min, max, std, nunique (distinct values), first and last.

The difference between count and size matters when data has gaps: if two of a group's five rows have a missing bikes_out, count gives 3 and size gives 5.

Sometimes you want a group statistic next to each row instead of one row per group, for example each rental's share of its station's total. transform returns a result aligned to the original rows:

df["station_total"] = df.groupby("station")["bikes_out"].transform("sum")
df["share"] = df["bikes_out"] / df["station_total"]

Step 5 of 13Practice · Match the pairs

Match each aggregation to what it returns for a group.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. size
  2. count
  3. nunique
  4. median
  5. transform("mean")

Step 6 of 13Learn

Counting and pivot tables

Counting categories is so common that it has its own method:

df["station"].value_counts()
# Harbor    3
# Market    2
# Park      1
df["station"].value_counts(normalize=True)   # shares instead of counts: 0.5, 0.33, 0.17

Results are sorted from most to least frequent, and NaN is excluded unless you pass dropna=False.

Pivot tables reshape a grouping with two keys into a grid, one key down the rows and the other across the columns:

pd.pivot_table(df, values="bikes_out", index="station",
               columns="hour", aggfunc="sum", fill_value=0)
# hour     8   9
# Harbor  14  16
# Market   9  13
# Park     0  11

That's equivalent to df.groupby(["station", "hour"])["bikes_out"].sum().unstack(fill_value=0). Pivot tables are ideal for reports and heatmaps. pd.crosstab(df["station"], df["hour"]) does the same for simple counts.

A common analysis pattern ties these together: filter to the rows you care about, group by the dimension of interest, aggregate, then sort the result: df[df["hour"] < 10].groupby("station")["bikes_out"].sum().sort_values(ascending=False).

Long table versus wide pivot tableLong (one row per observation)HarborMon14HarborTue6ParkMon11ParkTue9pivot_tablemelt ←Wide (one row per station)MonTueHarbor146Park119

Step 7 of 13Practice · Work it out

A survey column has 200 answers: 90 "yes", 70 "no" and 40 "unsure". What value does value_counts(normalize=True) show for "no"?

Step 8 of 13Learn

Grouping by time

Time is the most common grouping dimension of all: revenue per month, rentals per hour, signups per week. Once a column is a proper datetime, pandas offers two convenient approaches.

Extract a time part and group by it:

df["month"] = df["start_time"].dt.to_period("M")
df.groupby("month")["bikes_out"].sum()

df.groupby(df["start_time"].dt.hour)["bikes_out"].mean()   # average by hour of day

Resample a time series by setting the datetime as the index:

daily = df.set_index("start_time")["bikes_out"].resample("D").sum()
weekly = df.set_index("start_time")["bikes_out"].resample("W").sum()

Resampling creates a row for every period in the range, including periods with no data, which then show 0 for sums or NaN for means. That's usually what you want for charts, because silently skipping empty days would make a line chart misleading.

Rolling windows smooth noisy daily data: daily.rolling(7).mean() gives a 7-day moving average, where each value averages that day and the six before it. The first six values are NaN, because a full window isn't available yet. Moving averages make weekly patterns and trends much easier to see.

Daily rentals (bars) and the 7-day rolling mean (line), illustrative datafirst 6 days: NaN (no full window)smooth trend without weekend spikes

Step 9 of 13Practice · Work it out

A daily series starts on March 1. With rolling(7).mean(), how many of the first values are NaN because a full 7-day window isn't available yet?

Step 10 of 13Note

Step 11 of 13Note

Step 12 of 13Practice · True or false

By default, df.groupby("region") drops rows where region is missing, so they don't appear in any group's results.

Step 13 of 13Practice · Choose one

Which code gives the total revenue per month, sorted from highest to lowest?