Rana Maninder Singh
Lesson 4 of 12Data Analysis with Python

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

ResourceLink
PreviousPandas basics
NextMerge


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.

Python EDA cheat sheet
Python EDA cheat sheet

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:

Use this when: breaking revenue down by sales channel or month.

MethodMeaning
.sum(), .mean(), .count()Common aggregates
.agg([...])Several at once
.size()Row count per group
.first(), .last()First/last row per group

Gotcha — groupby drops NaN keys by default. Rows where the grouping column is missing are excluded from every group, with no warning. Totals from groupby(...).sum() can be less than df["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 disappears

Fix: 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:

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:

Use this when: finance wants a month-by-channel grid like their Excel pivot.

ArgumentRole
valuesNumbers to aggregate
indexRow labels
columnsColumn labels
aggfuncsum, mean, count, …
fill_valueReplace 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:

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:

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:

Use this when: marketing wants L/M/H bands or equal-sized customer quartiles.

FunctionBins by
cutFixed edges you define
qcutQuantiles — 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.days

Breaking it down:

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 index

Breaking it down:

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:

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:

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:

Use this when: account management wants names and segments for the top five accounts.


Pandas analysis command reference

CategoryAPIUse
groupby.groupby().sum/mean/agg/sizeSQL GROUP BY
Pivotpivot_tableCross-tab sums
ReshapemeltUnpivot
Countscrosstab, value_countsFrequencies
Binscut, qcutBands / quartiles
Datesto_datetime, .dt.*, resampleTime analysis
Top-Nnlargest, groupby().head(n)Rankings

Essential commands

Command / actionWhat 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.qcutBucket numeric columns.
pd.to_datetime, .dt accessorParse 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

  • [ ] groupby with multiple columns or named agg
  • [ ] pivot_table with sensible fill_value
  • [ ] cut or qcut used
  • [ ] to_datetime and one .dt field
  • [ ] Ready for Merge