pandas in depth · lesson 2 of 12
Parts in this lesson
Agroupby("store")["kilos"].transform("sum")the group’s answer, on every row
Bgroupby("store").filter(test)keep whole groups
Cgroupby("store")["kilos"].cumsum()a running total per group

Transform and filter by group

Last updated

groupby with agg shrinks each group to one row. Often you want the opposite: keep every row, and add something about its group, such as the store's total or the day's average, so each row can be compared with it. In this lesson you'll do that with transform, keep or drop whole groups with filter, and rank and add up within groups.

By the end of this lesson you can

  • Add a group's total or mean to every row with transform
  • Work out each row’s share of its group, and its distance from the group mean
  • Keep only the groups that pass a test, with filter
  • Rank and keep running totals within groups

Every row and its group

Step through, then run the first two cells.

A group’s total copied back to its rows. Rice sales, two days, three stores. Each store’s total is easy: agg gives three numbers. But you want a total on every row, to compare each day with it.Batangas42Lipa35Tanauan29Batangas38Lipa33Tanauan30Batangas80Lipa68Tanauan59ricestorekilosstore_totalsum per store
1 of 3 Rice sales, two days, three stores. Each store’s total is easy: agg gives three numbers. But you want a total on every row, to compare each day with it.
transform.ipynb
  • transform("sum") gives an answer the same length as the table: each row gets its own store's total. So kilos / store_total is each day's share of its store's rice, worked out row by row.
  • transform("mean") grouped by date gives each day's average across stores. Subtracting it says how far each store was above or below that day's average: Batangas 6.7 kg above on 2 January, Tanauan 6.3 below. That's lesson 2.9's "compare with the mean", done by group.

(.copy() on the first line makes rice a table of its own, so adding columns to it is clearly meant to change only rice. Lesson 3.6 explains why pandas cares.)

Filter, rank and running totals

The last two cells of the notebook above:

  • filter(lambda g: g["kilos"].sum() > 80) keeps whole groups that pass a test, and drops the others. Tanauan sold 74 kg in all, so all of its rows are gone; Batangas and Lipa keep every row. The lambda g: is a small function: g is one store's rows at a time.
  • rank within groups: each row's place inside its own store. Batangas's rice on 2 January is its best line, rank 1.
  • cumsum within groups: a running total that starts again for each store.

Both keep the table's shape, like transform, so they can be added as columns.

Wrong way: agg where transform was meant

You want each store's total on every row, and write the groupby you know. Run the cells.

totals.ipynb

The new column is all NaN. No error. The second cell shows why: groupby(...).sum() gives three numbers labelled Batangas, Lipa, Tanauan. The table's rows are labelled 0 to 11. When pandas puts a Series into a column, it matches labels (lesson 3.1), and no label matches, so every row gets NaN.

transform("sum"), in the last cell, gives twelve numbers labelled 0 to 11, so they line up. The rule: agg when you want one row per group; transform when you want one value per original row.

Check what you learned

A table has 300 rows and 5 stores. How many values does groupby("store")["kilos"].transform("mean") give?
You want only the stores that had at least 20 days of sales, with all their rows. Which do you use?
df["total"] = df.groupby("store")["kilos"].sum() fills the column with NaN. Why?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Data Analysis