Data Analysis · pandas Core · lesson 9 of 12
Grouping
about 16 minutes · free · runs in your browser
Step 1 of 2
Split, apply, combine
groupby is the single most useful thing in pandas. It splits the rows into groups,
applies an aggregation to each, and combines the answers:
df.groupby("country")["sales"].sum()
df.groupby("country")["sales"].mean()
df.groupby("country").size() # rows per group
Group by several columns for a finer breakdown, and use .agg when one aggregation is
not enough:
df.groupby(["country", "year"])["sales"].sum()
df.groupby("country")["sales"].agg(["sum", "mean", "count"])
The result is indexed by the grouping key. .reset_index() turns that index back into
an ordinary column, which is usually what you want before printing or exporting.
Your turn: total the sales per region, and find which region sold most.
You start from this, and edit it in the browser:
import pandas as pd
df = pd.DataFrame({
"region": ["north", "south", "north", "east", "south", "north"],
"sales": [100, 250, 175, 90, 120, 60],
})
# Set totals (a dict of region -> total) and best_region.
Step 2 of 2
Several aggregations at once
.agg takes a dictionary mapping each column to what you want from it:
df.groupby("region").agg({"sales": "sum", "units": "mean"})
Your turn: write summarise(df) returning, per region, the total sales and the
number of rows, as a dictionary of the form
{"north": {"sales": 335, "orders": 3}, ...}.
You start from this, and edit it in the browser:
import pandas as pd
def summarise(df):
# Return {region: {"sales": total, "orders": row count}}
pass