Pandas Analysis
Lesson opener
In one line: Groupby in depth, pivot_table, reshape (melt), crosstab, binning (cut / qcut), and datetime analysis - Excel pivot and SQL GROUP BY in pandas form.
Why it matters: This shows up at work when you need to groupby in depth, pivot_table, reshape (melt), crosstab, binning (cut / qcut), and datetime analysis - Excel pivot and SQL GROUP BY in pandas form..
Before this lesson: Pandas basics
Before you start
| Resource | Link |
|---|---|
| Previous | Pandas basics |
| Next | Merge |
What you will learn
groupby in depth, pivot_table, reshape (melt), crosstab, binning (cut / qcut), and datetime analysis — Excel pivot and SQL GROUP BY in pandas form.

groupby — single and multiple keys
[groupby single and multiple keys]
WHY groupby is how you answer 'by channel' or 'by month and channel' questions.
WHEN Use whenever SQL would say GROUP BY.
import pandas as pd
sales = pd.read_csv("data/sales.csv")
sales.groupby("channel")["revenue"].sum()
sales.groupby("channel")["revenue"].agg(["sum", "mean", "count"])
sales.groupby(["month", "channel"], as_index=False)["revenue"].sum()Breaking it down:
.groupby('channel')['revenue'].sum()— one key.groupby(['month','channel'])— two keys.agg(['sum','mean','count'])— multiple metrics
Use this when: breaking revenue down by sales channel or month.
| Method | Meaning |
|---|---|
.sum(), .mean(), .count() | Common aggregates |
.agg([...]) | Several at once |
.size() | Row count per group |
.first(), .last() | First/last row per group |
Gotcha —
groupbydrops NaN keys by default. Rows where the grouping column is missing are excluded from every group, with no warning. Totals fromgroupby(...).sum()can be less thandf["revenue"].sum()if the key has nulls.
import pandas as pd
sales = pd.read_csv("data/sales.csv")
dirty = sales.head(8).copy()
dirty.loc[0:1, "channel"] = None # simulate a dirty import
dirty["revenue"].sum() # full total — includes the two NaN-channel rows
dirty.groupby("channel")["revenue"].sum()
# NaN-channel revenue missing from the result — silent undercount
dirty.groupby("channel", dropna=False)["revenue"].sum()
# includes an explicit NaN group so nothing disappearsFix: pass dropna=False when a missing category should count as its own bucket (or clean/impute the key first in Missing values).
Named aggregations (clear column names):
[named aggregations]
WHY Named agg gives clear output column names instead of MultiIndex headaches.
WHEN Use when returning several metrics from one groupby.
sales.groupby("channel").agg(
total_rev=("revenue", "sum"),
orders=("order_id", "count"),
avg_rev=("revenue", "mean"),
)Breaking it down:
total_rev=('revenue','sum')— named output columnorders=('order_id','count')— count orders per group
Use this when: building a summary table for a stakeholder who hates weird column headers.
pivot_table (Excel pivot / SQL pivot)
[pivot_table]
WHY Excel pivot in one call — rows, columns, and aggfunc.
WHEN Use for cross-tabs like month × channel revenue.
pd.pivot_table(
sales,
values="revenue",
index="month",
columns="channel",
aggfunc="sum",
fill_value=0,
margins=True,
)Breaking it down:
values='revenue'— numbers to aggregateindex/columns— row and column labelsfill_value=0— replace NaN with zero
Use this when: finance wants a month-by-channel grid like their Excel pivot.
| Argument | Role |
|---|---|
values | Numbers to aggregate |
index | Row labels |
columns | Column labels |
aggfunc | sum, mean, count, … |
fill_value | Replace NaN in result |
melt (wide → long)
[melt wide to long]
WHY Unpivot when metrics sit in separate columns but charts need one value column.
WHEN Use before some seaborn plots or stacked long-format exports.
customers = pd.read_csv("data/customers.csv")
pd.melt(
customers,
id_vars=["customer_id", "segment"],
value_vars=["total_revenue", "monthly_spend"],
var_name="metric",
value_name="amount",
)Breaking it down:
id_vars— keys to keepvalue_vars— columns to stackvar_name/value_name— new column names
Use this when: total_revenue and monthly_spend are columns but you need one 'metric' column.
Opposite of pivot — one row per metric per customer.
crosstab (frequency table)
[crosstab]
WHY Two-way frequency table — segment vs churned counts.
WHEN Use for quick chi-square style EDA.
customers = pd.read_csv("data/customers.csv")
pd.crosstab(customers["segment"], customers["churned"], margins=True)Breaking it down:
pd.crosstab(a, b, margins=True)— counts with totals
Use this when: checking churn count by segment before a retention deck.
Like GROUP BY two dimensions with counts.
cut and qcut (bins)
[cut and qcut bins]
WHY cut uses your edges; qcut splits into equal-sized groups.
WHEN Use for revenue bands or quartile segments.
customers = pd.read_csv("data/customers.csv")
pd.cut(
customers["total_revenue"],
bins=[0, 500, 1500, 5000],
labels=["L", "M", "H"],
)
pd.qcut(customers["total_revenue"], q=4, labels=["Q1", "Q2", "Q3", "Q4"])Breaking it down:
pd.cut(..., bins=[...], labels=[...])— fixed bucketspd.qcut(..., q=4)— quartiles
Use this when: marketing wants L/M/H bands or equal-sized customer quartiles.
| Function | Bins by |
|---|---|
cut | Fixed edges you define |
qcut | Quantiles — equal-sized groups |
datetime
[datetime parsing]
WHY to_datetime unlocks .dt.year, .dt.month, tenure calculations.
WHEN Run on any date column loaded as object/string.
customers["signup_date"] = pd.to_datetime(customers["signup_date"])
customers["signup_date"].dt.year
customers["signup_date"].dt.month
customers["signup_date"].dt.day_name()
customers["tenure_days"] = (pd.Timestamp.today() - customers["signup_date"]).dt.daysBreaking it down:
pd.to_datetime(...)— parse strings to timestamps.dt.year,.dt.month— extract parts- tenure_days from subtracting signup from today
Use this when: cohort analysis needs signup year or customer age in days.
On sales with month as string 2022-06:
[resample on month index]
WHY resample aggregates time series when index is datetime.
WHEN Use after parsing month and setting it as index.
sales["month"] = pd.to_datetime(sales["month"])
sales.set_index("month").resample("ME")["revenue"].sum() # monthly total if daily indexBreaking it down:
.set_index('month').resample('ME')['revenue'].sum()— monthly totals
Use this when: sales.csv has daily-ish data indexed by date and you need monthly rollups.
Top-N per group
[Top-N per group]
WHY nlargest globally vs head per group after sort — different questions.
WHEN Use groupby().head(3) for top 3 orders per channel.
customers.nlargest(5, "total_revenue")
sales.sort_values("revenue", ascending=False).groupby("channel").head(3)Breaking it down:
.nlargest(5, 'total_revenue')— global top 5.sort_values(...).groupby('channel').head(3)— top 3 per channel
Use this when: 'best customers overall' vs 'best three orders per channel'.
Case study 1 — revenue by segment × month
[case study segment x month]
WHY Merge then groupby — same as SQL JOIN + GROUP BY.
WHEN Use when revenue is on sales but segment is on customers.
customers = pd.read_csv("data/customers.csv")
sales = pd.read_csv("data/sales.csv")
df = sales.merge(customers[["customer_id", "segment"]], on="customer_id")
df.groupby(["segment", "month"], as_index=False)["revenue"].sum()
# or pivot_table(df, values='revenue', index='segment', columns='month', aggfunc='sum')Breaking it down:
sales.merge(customers[...], on='customer_id')— attach segment.groupby(['segment','month'])['revenue'].sum()— totals
Use this when: the ask is revenue by segment and month and they live on different tables.
Case study 2 — top 5 customers by revenue
[case study top 5 customers]
WHY groupby customer, sum revenue, nlargest, merge back for attributes.
WHEN Classic 'who are our whales' analysis.
top = (
sales.groupby("customer_id")["revenue"]
.sum()
.nlargest(5)
.reset_index(name="recent_revenue")
)
top.merge(customers, on="customer_id")Breaking it down:
.groupby('customer_id')['revenue'].sum()— total per customer.nlargest(5)— top five.reset_index(name='recent_revenue')— name the sum something other thantotal_revenueso the merge does not collide withcustomers.total_revenue(pandas would otherwise silently emittotal_revenue_x/total_revenue_y).merge(customers)— add segment and churn (and the customer's owntotal_revenuealongsiderecent_revenue)
Use this when: account management wants names and segments for the top five accounts.
Pandas analysis command reference
| Category | API | Use |
|---|---|---|
| groupby | .groupby().sum/mean/agg/size | SQL GROUP BY |
| Pivot | pivot_table | Cross-tab sums |
| Reshape | melt | Unpivot |
| Counts | crosstab, value_counts | Frequencies |
| Bins | cut, qcut | Bands / quartiles |
| Dates | to_datetime, .dt.*, resample | Time analysis |
| Top-N | nlargest, groupby().head(n) | Rankings |
Essential commands
| Command / action | What it does |
|---|---|
groupby(cols).agg(...) | Multiple metrics per group. |
groupby(..., as_index=False) | Keep groups as columns. |
pd.pivot_table(...) | Spread values across columns. |
pd.melt(...) | Long format from wide. |
pd.crosstab(a, b) | Two-way frequency table. |
pd.cut / pd.qcut | Bucket numeric columns. |
pd.to_datetime, .dt accessor | Parse and part dates. |
nlargest, groupby().head() | Top rows per group. |
Practice
Do this now: Notebook ds06_pandas_analysis.ipynb — both case studies; one pivot_table; one cut or qcut; export one CSV to outputs/.
Checklist
- [ ]
groupbywith multiple columns or namedagg - [ ]
pivot_tablewith sensiblefill_value - [ ]
cutorqcutused - [ ]
to_datetimeand one.dtfield - [ ] Ready for Merge