Sub topic 2
Your first groupby
This chapter shows how to call groupby, what object it returns, and how that object becomes a result. It assumes you can build a DataFrame, select columns with df["col"], and read a Series with its index. The previous chapter introduced split-apply-combine. Here you run it.
The shape of a groupby call
Most groupby code has three parts, read left to right:
df.groupby("region")chooses the key that defines the groups.["revenue"]chooses which column to work on..sum()chooses what to compute for each group.
Here is a complete example. Every later example in this chapter reuses this DataFrame.
import pandas as pd
df = pd.DataFrame({
"region": ["North", "North", "South", "South", "South"],
"product": ["A", "B", "A", "A", "B"],
"units": [10, 5, 7, 3, 8],
"revenue": [100.0, 75.0, 70.0, 30.0, 120.0],
})
totals = df.groupby("region")["revenue"].sum()
print(totals)
# region
# North 175.0
# South 220.0
# Name: revenue, dtype: float64The result is a Series. Its index holds the group keys (North, South), and its values are the per-group sums. The index is named region, after the column you grouped by.
The three steps map onto split-apply-combine like this:
The GroupBy object is lazy
df.groupby("region") does not compute anything you can read. It returns a DataFrameGroupBy object, which records which rows belong to which group. The work happens when you call an aggregation such as sum().
This is why you can store the object and reuse it:
import pandas as pd
df = pd.DataFrame({
"region": ["North", "North", "South", "South", "South"],
"product": ["A", "B", "A", "A", "B"],
"units": [10, 5, 7, 3, 8],
"revenue": [100.0, 75.0, 70.0, 30.0, 120.0],
})
g = df.groupby("region")
print(type(g).__name__)
# DataFrameGroupBy
print(g.ngroups)
# 2
print(len(g))
# 2
print(g["revenue"].sum())
# region
# North 175.0
# South 220.0
# Name: revenue, dtype: float64
print(g["units"].max())
# region
# North 10
# South 8
# Name: units, dtype: int64Two attributes are handy for checking your setup. ngroups is the number of groups, and len(g) gives the same number. If ngroups is not what you expect, the key column probably has unexpected values, such as trailing spaces or inconsistent capitalization.
Indexing a GroupBy with a column name returns a SeriesGroupBy. It is the same grouping, narrowed to one column.
| Expression | Type returned | What it represents |
|---|---|---|
| `df.groupby("region")` | `DataFrameGroupBy` | All columns, split by region |
| `df.groupby("region")["revenue"]` | `SeriesGroupBy` | One column, split by region |
| `df.groupby("region")[["units", "revenue"]]` | `DataFrameGroupBy` | Two columns, split by region |
Passing a list inside the brackets keeps the result a DataFrame:
import pandas as pd
df = pd.DataFrame({
"region": ["North", "North", "South", "South", "South"],
"product": ["A", "B", "A", "A", "B"],
"units": [10, 5, 7, 3, 8],
"revenue": [100.0, 75.0, 70.0, 30.0, 120.0],
})
print(df.groupby("region")[["units", "revenue"]].sum())
# units revenue
# region
# North 15 175.0
# South 18 220.0What happens without a column selection
You can aggregate without choosing a column. Then pandas applies the function to every column that is not a grouping key:
import pandas as pd
df = pd.DataFrame({
"region": ["North", "North", "South", "South", "South"],
"product": ["A", "B", "A", "A", "B"],
"units": [10, 5, 7, 3, 8],
"revenue": [100.0, 75.0, 70.0, 30.0, 120.0],
})
print(df.groupby("region").sum())
# product units revenue
# region
# North AB 15 175.0
# South AAB 18 220.0Look at the product column. Summing strings concatenates them, so you get AB and AAB. The call succeeds, but the column is meaningless. Other functions behave worse: df.groupby("region").mean() raises a TypeError because the product strings cannot be averaged.
Two habits avoid both problems:
- Select the columns you want before aggregating, as in the earlier examples.
- When you do want every numeric column, pass
numeric_only=True, for exampledf.groupby("region").mean(numeric_only=True).
Grouping happens on the key values
The groups are defined by the distinct values in the key. Rows with equal keys go in the same group, wherever they sit in the DataFrame. Rows 2, 3 and 4 are not contiguous with rows 0 and 1 in any special way. The row order of df does not matter for which group a row joins.
By default, groups appear in the result sorted by key. Here North comes before South, and numeric keys are ordered numerically. The chapter on missing keys and group ordering covers sort=False and what happens to rows whose key is missing. For now, note that the default result is a Series ordered by its key.
Reading the result
The result of a groupby aggregation is an ordinary pandas object. You can index it like any other Series:
import pandas as pd
df = pd.DataFrame({
"region": ["North", "North", "South", "South", "South"],
"product": ["A", "B", "A", "A", "B"],
"units": [10, 5, 7, 3, 8],
"revenue": [100.0, 75.0, 70.0, 30.0, 120.0],
})
totals = df.groupby("region")["revenue"].sum()
print(totals["South"])
# 220.0
print(totals.idxmax())
# South
print(totals.sort_values(ascending=False))
# region
# South 220.0
# North 175.0
# Name: revenue, dtype: float64
print(totals.index.tolist())
# ['North', 'South']The group keys live in the index, not in a column. That is the default shape when you group by one column and select a single column. The chapter on result shape explains how to turn the keys back into a column with as_index=False or reset_index().
Common mistakes
| Mistake | What you see | Fix |
|---|---|---|
| Forgetting the aggregation: `df.groupby("region")` alone | A `DataFrameGroupBy` object, not data | Add a method such as `.sum()` |
| Using `df.groupby("Region")` when the column is `region` | `KeyError: 'Region'` | Match the column name exactly |
| Aggregating all columns with `mean()` when text columns exist | `TypeError` | Select numeric columns or use `numeric_only=True` |
| Writing `df.groupby["region"]` with square brackets | `TypeError` because `groupby` is a method | Call it with parentheses |
| Expecting the keys to be a column in the result | `totals["region"]` raises `KeyError` | Use the index, or reset it |
A quick way to inspect a result you did not expect is to check type(...), .ndim, and .index.names. A GroupBy object, a Series, and a DataFrame all print differently, and the type tells you which step you are at.
Exercises
Exercise
Using the DataFrame df from this chapter, write one expression that returns the total units for each product, and give the values it returns.
Show answer
df.groupby("product")["units"].sum(). Product A has units 10 + 7 + 3 = 20, and product B has units 5 + 8 = 13, so the result is a Series indexed by product with A = 20 and B = 13, dtype int64.
Exercise
Why does df.groupby("region").sum() return a product column containing AB and AAB, and how would you avoid that column while still getting the numeric totals?
Show answer
Without a column selection, pandas applies sum to every non-key column, and summing strings concatenates them. Select the numeric columns first, as in df.groupby("region")[["units", "revenue"]].sum(), or pass numeric_only=True.