Sub topic 2
Your first groupby
This chapter assumes you can build a DataFrame, select columns, and read a pandas index. It covers the basic groupby call and what it returns.
The idea in one call
groupby splits a DataFrame into groups of rows that share a key value. It then applies a function to each group and combines the results into one object. This is the split-apply-combine pattern.
A first example
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 expression has three parts:
df.groupby("region")names the key column.["revenue"]selects the column to summarize..sum()is the aggregation.
The result is a Series. Its index holds the group keys, North and South, and its values are the sums.
The GroupBy object is lazy
df.groupby("region") does not compute anything. It returns a GroupBy object that remembers how the rows would be split. The work happens when you call an aggregation on it.
grouped = df.groupby("region")
print(type(grouped))
# <class 'pandas.core.groupby.generic.DataFrameGroupBy'>
print(grouped.ngroups)
# 2
print(type(grouped["revenue"]))
# <class 'pandas.core.groupby.generic.SeriesGroupBy'>Selecting one column with grouped["revenue"] gives a SeriesGroupBy. Selecting several columns with a list gives a DataFrameGroupBy. You can store the object in a variable and reuse it for several aggregations. This avoids repeating the key.
Aggregating every column
If you skip the column selection, pandas applies the function to every remaining column. Here product holds strings, and summing strings concatenates them. Restrict the call to numeric columns:
print(grouped.sum(numeric_only=True))
# units revenue
# region
# North 15 175.0
# South 18 220.0Selecting the columns you want, as in grouped[["units", "revenue"]].sum(), states your intent more clearly than numeric_only=True.
Common errors
- A
KeyErroron the key column. The name must match a column exactly, including case and spaces. - Unexpected string results. Calling
sum()on a whole GroupBy that contains text columns concatenates the strings, or raises an error, depending on the pandas version. Select the numeric columns first. - Expecting a DataFrame. Selecting one column with a single string gives a Series result. Use
[["revenue"]]to get a one-column DataFrame. - Forgetting the aggregation. Printing
df.groupby("region")shows only the object's repr, not any data.
Check your understanding
Exercise
Using the df from this chapter, write one expression that returns the total units sold per product. Which values does the result contain?
Show answer
df.groupby("product")["units"].sum() returns a Series indexed by product. A is 10 + 7 + 3 = 20, and B is 5 + 8 = 13.
Exercise
Why does df.groupby("region") print no numbers when you run it on its own?
Show answer
It returns a lazy GroupBy object that only records how to split the rows. Nothing is computed until you call an aggregation such as sum() on it.