25. pandas advanced
Module 24 taught you to load a table, select rows and columns and add new columns. Real questions need more: “revenue per region”, “each store’s share of its region”, “a month-by-category report”, “sales with the store’s city attached”, “a 7-day average of daily revenue”. This module gives you the pandas tools for these questions. You use the course sales data: 20,228 order lines from 12 stores, plus the stores, products, customers and web-traffic tables.
What you will learn
Section titled “What you will learn”- Summarize groups with
groupbyandagg, name the result columns with named aggregation, and broadcast group results back to rows withtransform. - Keep or drop whole groups with
filter, and control empty categories withobserved. - Reshape between long and wide format with
pivot_table,pivot,crosstab,melt,stackandunstack. - Combine tables with
merge,joinandconcat, and check the join withvalidateandindicator. - Build, select from and flatten a
MultiIndex. - Smooth time series with
rolling,expandingandewm, clean text with.strand dates with.dt, write readable method chains and shrink a DataFrame’s memory.
Prerequisites
Section titled “Prerequisites”- 24. pandas fundamentals: Series, DataFrame,
read_csv,loc, boolean masks,query, new columns, dtypes and thecategorydtype. - 23. NumPy: vectorized operations and dtypes such as
int8andfloat32. - 05. Functions: lambda expressions and functions as arguments.
- 09. Standard library power tools: grouping with
defaultdictand rolling windows withdeque. - The course datasets in a
data/folder: Get the data.
Concepts
Section titled “Concepts”Setup: display options and the data
Section titled “Setup: display options and the data”Every pandas page of this course starts with the same display settings. They keep printed tables at most 100 characters wide and show 3 decimals.
import pandas as pd
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)Load the five tables of this module. parse_dates turns the date text into the datetime64 dtype, so the .dt tools work. index_col="date" makes the dates the row labels of web, which the window functions use later.
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])stores = pd.read_csv("data/stores.csv")products = pd.read_csv("data/products.csv")customers = pd.read_csv("data/customers.csv")web = pd.read_csv("data/web_traffic.csv", parse_dates=["date"], index_col="date")print(sales.shape, stores.shape, products.shape, customers.shape, web.shape)print(sales.dtypes)(20228, 13) (12, 5) (30, 6) (5000, 15) (1096, 5)order_id strorder_date datetime64[us]customer_id strstore_id strregion strchannel strproduct_id strproduct strcategory strunit_price float64quantity int64discount float64revenue float64dtype: objectText columns load as the pandas 3 str dtype, and order_date is a datetime64 column. sales is a fact table: one row per event (an order line), with ids that point to other tables. stores, products and customers are dimension tables: one row per thing, with its attributes (a city, a cost, a plan). Most analysis joins facts to dimensions and then summarizes.
Split-apply-combine with groupby
Section titled “Split-apply-combine with groupby”Most summary questions have the same shape: “for each region, compute the total revenue”. pandas answers them with split-apply-combine:
- Split the rows into groups by a group key, such as
region. - Apply a function to each group, such as
sum. - Combine the results into one new table.
flowchart LR
T["sales<br/>20,228 rows"] --> S{"split by region"}
S --> E["East rows"]
S --> N["North rows"]
S --> So["South rows"]
S --> W["West rows"]
E --> A["apply sum"]
N --> A
So --> A
W --> A
A --> C["combine:<br/>4 rows, one per region"]
groupby does the split. It returns a GroupBy object: a plan that remembers which rows belong to which group. It computes nothing until you ask for a result.
by_region = sales.groupby("region")print(type(by_region).__name__, by_region.ngroups)print(by_region["revenue"].sum())DataFrameGroupBy 4regionEast 993683.72North 888229.47South 891766.07West 822844.57Name: revenue, dtype: float64The group keys become the index of the result, sorted. Without pandas, you would write the loop of module 09 yourself. It gives the same totals, more slowly and in more lines:
totals: dict[str, float] = {}for region, revenue in zip(sales["region"], sales["revenue"]): totals[region] = totals.get(region, 0) + revenueprint({region: round(total, 2) for region, total in sorted(totals.items())}){'East': 993683.72, 'North': 888229.47, 'South': 891766.07, 'West': 822844.57}You can loop over a GroupBy object. Each step gives the key and a DataFrame with the rows of that group. This is useful to inspect groups, not to compute results:
for region, group in by_region: print(region, len(group), sorted(group["store_id"].unique()))East 5396 ['S07', 'S08', 'S09']North 4966 ['S01', 'S02', 'S03']South 5144 ['S04', 'S05', 'S06']West 4722 ['S10', 'S11', 'S12']Aggregate with agg and named aggregation
Section titled “Aggregate with agg and named aggregation”An aggregation reduces many values to one: a sum, a mean, a count. agg applies one or more aggregations to each group. A list of function names gives one column per function:
print(by_region["revenue"].agg(["sum", "mean", "max"])) sum mean maxregionEast 993683.72 184.152 4596.0North 888229.47 178.862 5196.0South 891766.07 173.360 4596.0West 822844.57 174.258 4596.0For a report, you want several columns, each from a different source column, with clear names. Named aggregation does this. Each keyword argument is new_name=(column, function):
summary = sales.groupby("region").agg( revenue=("revenue", "sum"), orders=("order_id", "nunique"), lines=("order_id", "size"), avg_line=("revenue", "mean"),)print(summary) revenue orders lines avg_lineregionEast 993683.72 4002 5396 184.152North 888229.47 3612 4966 178.862South 891766.07 3766 5144 173.360West 822844.57 3497 4722 174.258The names you choose become the columns. "nunique" counts distinct orders, because one order can have up to 3 lines. The common aggregation names:
| Name | Gives | Note |
|---|---|---|
"sum", "mean", "median" |
total, average, middle value | skip NaN |
"min", "max" |
smallest, largest | work on dates and text too |
"size" |
number of rows | counts NaN rows too |
"count" |
number of non-missing values | differs from size when there are NaN |
"nunique" |
number of distinct values | |
"std", "var" |
sample standard deviation, variance | divide by n − 1 |
"first", "last" |
first or last non-missing value in row order | skip NaN; sort first |
| a function or lambda | anything that maps a Series to one value | slower than a name |
Use a name such as "sum" when one exists. pandas runs it in fast compiled code. A lambda runs once per group in Python. Use a lambda only for a statistic with no name, such as the 90th percentile of line revenue:
p90 = sales.groupby("region")["revenue"].agg(lambda s: s.quantile(0.9))print(p90)regionEast 349.00North 340.20South 336.87West 348.66Name: revenue, dtype: float64By default, the keys go into the index. as_index=False keeps them as ordinary columns, which is what you want before a merge or an export:
by_store = sales.groupby("store_id", as_index=False).agg(revenue=("revenue", "sum"))print(by_store.head(3)) store_id revenue0 S01 406532.461 S02 268521.992 S03 213175.02transform: one result per row
Section titled “transform: one result per row”agg returns one row per group. Sometimes you need the group result on every original row. Example: what share of its region’s revenue does each store make? You need the region total next to each store. transform computes a group result and broadcasts it: it repeats the result on every row of the group, so the output has the same length and index as the input.
store_rev = sales.groupby(["region", "store_id"], as_index=False)["revenue"].sum()store_rev["region_total"] = store_rev.groupby("region")["revenue"].transform("sum")store_rev["share"] = store_rev["revenue"] / store_rev["region_total"]print(store_rev.head(6)) region store_id revenue region_total share0 East S07 468290.16 993683.72 0.4711 East S08 280682.49 993683.72 0.2822 East S09 244711.07 993683.72 0.2463 North S01 406532.46 888229.47 0.4584 North S02 268521.99 888229.47 0.3025 North S03 213175.02 888229.47 0.240The shares of S07, S08 and S09 add up to 1 (0.999 after rounding), as they must. In the North, Chicago (S01) makes 45.8% of the region’s revenue.
transform also standardizes values within a group. A z-score says how many standard deviations a value lies from the mean:
Here is one value, is the mean and is the standard deviation. A z-score of 3 means “3 standard deviations above the mean”, which is rare for most data. Computed within a group, it compares each value with its own group. A 300 USD line is ordinary for Electronics and huge for Books:
by_cat = sales.groupby("category")["revenue"]z = (sales["revenue"] - by_cat.transform("mean")) / by_cat.transform("std")cols = ["order_id", "category", "quantity", "revenue", "z"]print(sales.assign(z=z).nlargest(3, "z")[cols]) order_id category quantity revenue z4669 O003437 Books 20 699.80 16.9115421 O003982 Clothing 25 1499.75 15.36414802 O010887 Clothing 25 1499.75 15.364The top three are bulk orders of cheap products: quantities of 10 or more in categories where most lines have 1 unit.
agg |
transform |
filter |
|
|---|---|---|---|
| Output rows | one per group | one per input row | the input rows of the groups that pass |
| Output index | the group keys | the input index | the input index |
| Typical use | a report table | a share, a rank or a z-score within a group | drop small or incomplete groups |
filter: keep or drop whole groups
Section titled “filter: keep or drop whole groups”filter takes a function that receives one group as a DataFrame and returns True or False. It keeps all the rows of the groups that return True. Keep only the products with at least 1,000 order lines:
popular = sales.groupby("product_id").filter(lambda g: len(g) >= 1000)print(popular.shape)print(sorted(popular["product"].unique()))(3619, 13)['Cotton Bed Sheet Set', 'Organic Cotton T-Shirt', 'Wireless Earbuds']The result has the original rows and columns, not a summary. A mask built with transform gives the same rows. It avoids a Python call per group, so it is faster on many groups:
lines_per_product = sales.groupby("product_id")["order_id"].transform("size")print(sales[lines_per_product >= 1000].shape)(3619, 13)Categorical keys and observed
Section titled “Categorical keys and observed”The category dtype (module 24) stores a fixed list of allowed values, its categories. A category can exist with no rows. pd.cut makes such a column: it puts numbers into bins and returns a categorical. The course has no product priced between 500 and 1,000 USD:
price_band = pd.cut(sales["unit_price"], bins=[0, 25, 100, 500, 1000, 1500])print(price_band.dtype)print(sales.groupby(price_band, observed=False)["order_id"].size())print(sales.groupby(price_band, observed=True)["order_id"].size())categoryunit_price(0, 25] 5651(25, 100] 7656(100, 500] 5962(500, 1000] 0(1000, 1500] 959Name: order_id, dtype: int64unit_price(0, 25] 5651(25, 100] 7656(100, 500] 5962(1000, 1500] 959Name: order_id, dtype: int64The parameter observed decides what to do with categories that have no rows. observed=False keeps them and shows a size of 0. observed=True shows only the categories that appear in the data. In pandas 3, observed=True is the default. Older pandas versions used observed=False, so you meet both in other people’s code.
Empty categories matter most with two or more categorical keys. With observed=False, pandas builds every combination of the categories, even impossible ones such as a North store in the West:
cat_sales = sales.astype({"region": "category", "store_id": "category"})all_pairs = cat_sales.groupby(["region", "store_id"], observed=False)["revenue"].sum()real_pairs = cat_sales.groupby(["region", "store_id"], observed=True)["revenue"].sum()print(len(all_pairs), len(real_pairs))48 124 regions × 12 stores give 48 rows, and 36 of them are zeros. Pass observed=False only when you want the empty groups on purpose, for example a complete price-band report.
Long and wide data
Section titled “Long and wide data”The same numbers can be laid out in two shapes:
- Long format has one row per observation and one column per variable:
region,quarter,revenue. It is easy to filter, group and plot. Most pandas tools expect it. - Wide format spreads one variable across columns: one row per region, one column per quarter. It is easy for a person to read and compare. Reports and spreadsheets use it.
| region | quarter | revenue |
|---|---|---|
| East | 1 | 189,958 |
| East | 2 | 211,602 |
| North | 1 | 138,724 |
| North | 2 | 200,930 |
| region | 1 | 2 |
|---|---|---|
| East | 189,958 | 211,602 |
| North | 138,724 | 200,930 |
Reshaping moves data between the two shapes without changing the values:
flowchart LR
L["Long format<br/>region · quarter · revenue<br/>one row per observation"]
W["Wide format<br/>one row per region<br/>one column per quarter"]
L -- "pivot<br/>pivot_table<br/>unstack" --> W
W -- "melt<br/>stack" --> L
pivot_table, pivot and crosstab
Section titled “pivot_table, pivot and crosstab”A pivot table groups by one key for the rows and one key for the columns, and aggregates a value in each cell. pivot_table is groupby plus unstack in one call:
sales["year"] = sales["order_date"].dt.yearby_cat_year = sales.pivot_table( index="category", columns="year", values="revenue", aggfunc="sum", margins=True, margins_name="Total",)print(by_cat_year.div(1000).round(1))year 2023 2024 TotalcategoryBeauty 65.0 85.4 150.4Books 49.5 57.4 106.9Clothing 144.0 170.7 314.7Electronics 868.2 939.9 1808.1Home 274.4 397.8 672.3Sports 244.5 299.6 544.1Total 1645.6 1950.9 3596.5margins=True adds margins: a total row and a total column. .div(1000) shows thousands of USD, which keeps the table short. The default aggfunc is "mean", not "sum". Always pass it.
fill_value replaces the empty cells. Store S12 (Denver) opened on 2023-06-15, so it has no orders in the first quarter of 2023:
quarter = sales["order_date"].dt.to_period("Q").rename("quarter")west = sales[sales["region"] == "West"]orders_q = west.pivot_table( index="store_id", columns=quarter, values="order_id", aggfunc="nunique", fill_value=0,)print(orders_q)quarter 2023Q1 2023Q2 2023Q3 2023Q4 2024Q1 2024Q2 2024Q3 2024Q4store_idS10 180 205 166 234 159 197 190 288S11 112 148 146 185 116 154 146 225S12 0 17 84 121 84 79 105 156Without fill_value=0, that cell would be NaN. Here 0 is the true count. Use fill_value only when an empty cell really means zero.
pivot reshapes without aggregating. Each (index, column) pair must appear once. If a pair appears twice, pivot cannot choose a value and raises an error:
print(sales.pivot(index="region", columns="channel", values="revenue"))ValueError: Index contains duplicate entries, cannot reshapeEach region has thousands of online lines, so pivot fails. Use pivot for data that already has one row per pair, such as a summary table. Use pivot_table when it must aggregate.
pd.crosstab counts how often each pair of values occurs. The result is a contingency table (a table of counts for two categorical variables). normalize="index" turns each row into shares:
print(pd.crosstab(sales["region"], sales["channel"]))print(pd.crosstab(sales["region"], sales["channel"], normalize="index", margins=True))channel online storeregionEast 2277 3119North 2144 2822South 2123 3021West 1951 2771channel online storeregionEast 0.422 0.578North 0.432 0.568South 0.413 0.587West 0.413 0.587All 0.420 0.580About 42% of the lines in every region are online. crosstab takes Series, not column names, so it also works on arrays that are not in one DataFrame.
| Tool | Aggregates? | Duplicate pairs | Typical use |
|---|---|---|---|
df.pivot(index, columns, values) |
no | ValueError |
reshape a table that has one row per pair |
df.pivot_table(..., aggfunc=) |
yes (default mean) | aggregated | a report with totals (margins) |
pd.crosstab(a, b) |
counts (or aggfunc with values) |
counted | frequencies and shares of two categoricals |
groupby([a, b]).agg(...).unstack(b) |
yes | aggregated | several aggregations, then a wide view |
melt, stack and unstack
Section titled “melt, stack and unstack”melt goes from wide to long. id_vars names the columns that identify a row and stay as they are. The other columns become two columns: one for the old column name (var_name) and one for the value (value_name):
q_wide = sales.pivot_table( index="region", columns=quarter.dt.quarter, values="revenue", aggfunc="sum").round(0)q_long = q_wide.reset_index().melt( id_vars="region", var_name="quarter", value_name="revenue")print(q_wide)print(q_long.head(5))print(q_wide.shape, q_long.shape)quarter 1 2 3 4regionEast 189958.0 211602.0 226280.0 365844.0North 138724.0 200930.0 217431.0 331144.0South 158887.0 208892.0 218352.0 305635.0West 175192.0 161703.0 192389.0 293561.0 region quarter revenue0 East 1 189958.01 North 1 138724.02 South 1 158887.03 West 1 175192.04 East 2 211602.0(4, 4) (16, 3)4 regions × 4 quarters give 16 long rows. q_long.pivot(index="region", columns="quarter", values="revenue") rebuilds q_wide, because each pair now appears once.
stack and unstack reshape through the index instead of columns. unstack moves the innermost index level into the columns (long to wide). stack moves the columns into the innermost index level (wide to long):
rc = sales.groupby(["region", "channel"])["revenue"].sum().div(1000).round(1)print(rc)print(rc.unstack())print(rc.unstack().stack().equals(rc))region channelEast online 426.3 store 567.4North online 377.7 store 510.5South online 383.6 store 508.2West online 331.8 store 491.0Name: revenue, dtype: float64channel online storeregionEast 426.3 567.4North 377.7 510.5South 383.6 508.2West 331.8 491.0Trueunstack("region") would move the region level instead of the innermost one. In pandas 3, stack keeps rows with NaN values. Older versions dropped them by default.
Combine tables: merge, join and concat
Section titled “Combine tables: merge, join and concat”Tables share keys: columns whose values identify a row in another table, such as store_id. A merge (also called a join) matches rows of two tables on their keys and puts the columns side by side. The parameter how decides what happens to rows without a match:
how |
Keeps | SQL name |
|---|---|---|
"inner" (default) |
only keys found in both tables | INNER JOIN |
"left" |
every row of the left table; NaN where the right has no match | LEFT JOIN |
"right" |
every row of the right table | RIGHT JOIN |
"outer" |
every key of both tables | FULL OUTER JOIN |
Here is a small target table with a planned store S13 that has no sales yet. The indicator=True option adds a column _merge that says where each row came from: both, left_only or right_only.
store_totals = sales.groupby("store_id", as_index=False).agg(revenue=("revenue", "sum"))targets = pd.DataFrame( {"store_id": ["S01", "S02", "S13"], "target": [400_000, 250_000, 90_000]})for how in ["inner", "left", "right", "outer"]: merged = store_totals.merge(targets, on="store_id", how=how) print(how, len(merged))print(store_totals.merge(targets, on="store_id", how="outer", indicator=True).tail(3))inner 2left 12right 3outer 13 store_id revenue target _merge10 S11 268788.50 NaN left_only11 S12 152673.29 NaN left_only12 S13 NaN 90000.0 right_onlyThe cardinality of a join says how many rows on each side can share a key. Sales to stores is many-to-one: many sales lines point to one store. A many-to-one merge keeps the number of left rows. If the right table had a duplicate key by mistake, every matching left row would appear twice, and every total after the merge would be wrong. validate makes pandas check the cardinality and raise MergeError when it does not hold:
enriched = sales.merge( stores[["store_id", "city", "size_sqm"]], on="store_id", how="left", validate="many_to_one",)print(len(sales), len(enriched))print(enriched[["order_id", "store_id", "city", "size_sqm"]].head(3))20228 20228 order_id store_id city size_sqm0 O000001 S11 San Francisco 18901 O000002 S10 Seattle 24802 O000003 S05 Atlanta 2300The other values are "one_to_one", "one_to_many" and "many_to_many". When both tables have a column with the same name that is not a key, the merge adds the suffixes _x and _y. sales and stores both have region, so merge on both columns or select the columns you need first.
join is a merge on the index. It is short when the right table’s key is already its index. Its default is how="left", while merge defaults to "inner", so the same tables can give different row counts with the two tools:
store_info = stores.set_index("store_id")rev_per_sqm = ( sales.groupby("store_id")["revenue"].sum().to_frame() .join(store_info[["city", "size_sqm"]]))rev_per_sqm["per_sqm"] = rev_per_sqm["revenue"] / rev_per_sqm["size_sqm"]print(rev_per_sqm.head(3)) revenue city size_sqm per_sqmstore_idS01 406532.46 Chicago 2850 142.643S02 268521.99 Minneapolis 1950 137.704S03 213175.02 Detroit 1420 150.123pd.concat stacks tables instead of matching them. With the default axis=0, it puts the rows of the second table below the first. Use it to combine monthly files or yearly extracts with the same columns. ignore_index=True builds a fresh 0..n−1 index:
sales_2023 = sales[sales["year"] == 2023]sales_2024 = sales[sales["year"] == 2024]combined = pd.concat([sales_2023, sales_2024], ignore_index=True)print(len(sales_2023), len(sales_2024), len(combined))9081 11147 20228| Task | Tool |
|---|---|
| add columns from another table by a key column | merge(on=..., how=..., validate=...) |
| add columns by the index | join or merge(left_index=True, right_index=True) |
| put tables with the same columns one below the other | pd.concat([a, b]) |
| put Series or tables with the same index side by side | pd.concat([a, b], axis=1) |
MultiIndex
Section titled “MultiIndex”A MultiIndex is an index with two or more levels. Each row label is a tuple, such as ("North", "S01", 2024). You get one from a groupby on several keys, from set_index with several columns or from pd.MultiIndex.from_product:
rev = sales.groupby(["region", "store_id", "year"])["revenue"].sum().div(1000).round(1)print(rev.index.nlevels, rev.index.names)print(rev.head(4))3 ['region', 'store_id', 'year']region store_id yearEast S07 2023 204.4 2024 263.9 S08 2023 132.3 2024 148.4Name: revenue, dtype: float64pandas shows each label once and leaves the repeats blank, so the table is easy to read. Select with loc from the outermost level inward. A partial key returns the remaining levels; a full tuple returns one value:
print(rev.loc["North"].head(2))print(rev.loc[("North", "S01")])print(rev.loc[("North", "S01", 2024)])store_id yearS01 2023 185.6 2024 220.9Name: revenue, dtype: float64year2023 185.62024 220.9Name: revenue, dtype: float64220.9loc cannot skip the outer levels. xs (cross-section) selects by any level and drops it:
print(rev.xs(2024, level="year").head(4))region store_idEast S07 263.9 S08 148.4 S09 132.5North S01 220.9Name: revenue, dtype: float64pd.IndexSlice lets loc select on inner levels: : means “all values of this level”. With a single value in a level, pandas drops that level, as xs does. It needs a sorted index, which groupby gives you:
print(rev.loc[pd.IndexSlice[:, :, 2024]].head(3))region store_idEast S07 263.9 S08 148.4 S09 132.5Name: revenue, dtype: float64pd.MultiIndex.from_product builds every combination of some lists. Reindexing on it gives a complete grid, with a row even for combinations that have no data. Here every store gets all 24 months, and S12’s months before its opening get 0 orders:
order_month = sales["order_date"].dt.to_period("M").rename("month")grid = pd.MultiIndex.from_product( [sorted(sales["store_id"].unique()), sorted(order_month.unique())], names=["store_id", "month"],)orders_grid = ( sales.groupby(["store_id", order_month])["order_id"].nunique() .reindex(grid, fill_value=0))print(len(orders_grid), orders_grid.loc["S12"].head(7).to_list())288 [0, 0, 0, 0, 0, 17, 26]reset_index() turns the levels back into ordinary columns. Do this before you export to CSV, merge on the keys or hand the table to a plotting library:
print(rev.reset_index().head(3)) region store_id year revenue0 East S07 2023 204.41 East S07 2024 263.92 East S08 2023 132.3Window functions: rolling, expanding and ewm
Section titled “Window functions: rolling, expanding and ewm”A window function computes a value for each row from a group of neighboring rows, its window. On a time series, this smooths noise and shows the trend. Daily revenue jumps around: a Saturday with a TV sale can be four times a Tuesday.
daily = sales.groupby("order_date")["revenue"].sum()smooth = pd.DataFrame( { "revenue": daily, "ma7": daily.rolling(7).mean(), "ma7_min1": daily.rolling(7, min_periods=1).mean(), "cum": daily.expanding().sum(), "ewm7": daily.ewm(span=7, adjust=False).mean(), })print(smooth.head(8).round(1)) revenue ma7 ma7_min1 cum ewm7order_date2023-01-01 4767.0 NaN 4767.0 4767.0 4767.02023-01-02 1593.9 NaN 3180.5 6360.9 3973.72023-01-03 1811.8 NaN 2724.3 8172.8 3433.32023-01-04 2595.4 NaN 2692.0 10768.2 3223.82023-01-05 2615.4 NaN 2676.7 13383.5 3071.72023-01-06 1991.1 NaN 2562.4 15374.6 2801.52023-01-07 8015.8 3341.5 3341.5 23390.4 4105.12023-01-08 2815.8 3062.7 3062.7 26206.2 3782.8Three kinds of window:
rolling(7)uses the current row and the 6 rows before it: a trailing window of fixed size. The first 6 rows are NaN, because they have fewer than 7 values.min_periods=1computes with whatever values exist.center=Truecenters the window on the row instead; it uses future values, so do not use it for a forecast.expanding()uses every row from the start up to the current row.expanding().sum()is a running total, andexpanding().max()is the record so far.ewm()computes an exponentially weighted moving average (EWMA): an average in which each older value counts a bit less. It reacts to a change faster than a rolling mean of similar length.
The EWMA with adjust=False follows a simple rule. Each new average mixes the new value with the previous average :
With span=7, . Check the second row: 0.25 × 1,593.88 + 0.75 × 4,767.04 = 3,973.75, which the table rounds to 3973.7. Instead of span, you can set alpha directly or a half-life: the number of rows after which a value’s weight halves (halflife=7).
A window can also be a time span. rolling("7D") uses all rows in the last 7 days of a DatetimeIndex. It differs from rolling(7) when dates are missing: 7 rows could then cover more than 7 days.
The .str and .dt accessors
Section titled “The .str and .dt accessors”An accessor is an attribute that groups methods for one kind of data. .str holds the string methods of module 02, vectorized over a whole column. .dt holds date and time parts. In pandas 3, text columns have the str dtype. Missing text stays NaN through most .str methods; boolean methods such as contains return False for it.
names = products["product"]print(names.dtype)print(names.str.lower().head(3).to_list())print(names[names.str.contains("running", case=False)].to_list())print(products["product_id"].str[1:].astype(int).head(3).to_list())print(names.str.extract(r"(\d+)-(inch|Pack|Person)").dropna())str['wireless earbuds', 'noise-cancelling headphones', '55-inch 4k smart tv']['Running Socks 3-Pack', 'Trail Running Shoes'][1, 2, 3] 0 12 55 inch3 14 inch13 3 Pack19 2 Personstr.contains returns a boolean mask. str[1:] slices every value, so "P001" becomes "001". str.extract takes a regular expression (module 09) and returns one column per capturing group, with NaN where the pattern does not match.
order_date = sales["order_date"]print(order_date.dt.year.head(2).to_list(), order_date.dt.month.head(2).to_list())print(order_date.dt.day_name().head(2).to_list())print(order_date.dt.day_of_week.head(2).to_list())print(order_date.dt.to_period("M").head(2).to_list())print(order_date.dt.strftime("%Y-%m").head(2).to_list())[2023, 2023] [1, 1]['Sunday', 'Sunday'][6, 6][Period('2023-01', 'M'), Period('2023-01', 'M')]['2023-01', '2023-01']day_of_week counts from Monday = 0, so Sunday is 6. to_period("M") turns a date into its month, a period: a span of time, such as the whole of January 2023. It is the natural key for a monthly report. strftime formats dates as text, which is good for labels. It is slower, and the result is str, so the .dt tools no longer work on it. "%Y-%m" text still sorts correctly, but formats such as "%b %Y" ("Feb 2023") sort alphabetically, not by date.
| Accessor | Common methods |
|---|---|
.str |
lower, upper, strip, contains, startswith, replace, split(expand=True), extract, len, [a:b] |
.dt |
year, month, day, quarter, day_of_week, day_name(), to_period("M"), strftime, is_month_end |
.cat |
categories, codes, add_categories, rename_categories |
Method chaining with assign, pipe and query
Section titled “Method chaining with assign, pipe and query”Method chaining (module 02) calls one method on the result of the previous one. In pandas it turns an analysis into a recipe that reads from top to bottom, with no temporary variables. Three methods make chains work:
assign(name=value)returns a copy with a new or replaced column. With a lambda,assign(margin=lambda d: d["profit"] / d["revenue"]), the lambda receives the DataFrame at that point of the chain, including columns made earlier in the chain.query("condition")filters rows with an expression string.@nameuses a Python variable.pipe(func, *args)callsfunc(df, *args). It puts your own functions into the chain.
Wrap the chain in parentheses and put one step per line:
def add_profit(df: pd.DataFrame, products: pd.DataFrame) -> pd.DataFrame: """Add a profit column: revenue minus unit cost times quantity.""" unit_cost = df["product_id"].map(products.set_index("product_id")["unit_cost"]) return df.assign(profit=df["revenue"] - unit_cost * df["quantity"])
min_quantity = 2multi_unit = ( sales .query("channel == 'online' and quantity >= @min_quantity") .pipe(add_profit, products) .groupby("category") .agg(revenue=("revenue", "sum"), profit=("profit", "sum")) .assign(margin=lambda d: d["profit"] / d["revenue"]) .sort_values("margin", ascending=False))print(multi_unit) revenue profit margincategoryBeauty 43628.26 29929.26 0.686Books 29115.90 19413.60 0.667Clothing 83271.31 53965.41 0.648Sports 105925.46 61162.46 0.577Home 93574.76 52069.76 0.556Electronics 187802.25 69205.25 0.369Each line does one thing, so you can comment out a line to debug the chain. Copy-on-write (module 24) makes chains safe and cheap: every step returns a new object, pandas copies data only when something changes it, and the chain never changes sales. Do not use inplace=True in a chain; it returns None and breaks the next step.
Memory optimization
Section titled “Memory optimization”pandas keeps the whole table in memory. A table that fits easily today can fill your laptop’s memory next year. Module 24 measured columns with memory_usage(deep=True) and converted text to category. Here you optimize a whole table. Start with the largest columns:
memory = sales.memory_usage(deep=True)print(memory.sort_values(ascending=False).head(5))print(f"total: {memory.sum() / 1e6:.2f} MB")product 559679order_id 303420category 301833customer_id 283192channel 271459dtype: int64total: 3.33 MBThree tools shrink a table:
| Tool | For | Saving |
|---|---|---|
astype("category") |
text with few distinct values, such as region |
each value becomes a small integer code; the text is stored once |
pd.to_numeric(s, downcast="integer") |
integers with a small range, such as quantity |
int64 (8 bytes) to int8 (1 byte) |
astype("float32") |
measurements that need about 7 significant digits | 8 bytes to 4 bytes |
To downcast (module 24) is to convert a column to a smaller dtype that still holds every value. Text columns with low cardinality, few distinct values compared with the number of rows, gain most from category: region has 4 values in 20,228 rows. order_id has 14,877 distinct values, so a categorical saves little there. Example 8 applies all three tools.
Worked examples
Section titled “Worked examples”Example 1 — Build a regional KPI table
Section titled “Example 1 — Build a regional KPI table”Goal: The sales director wants one table with, per region: revenue, orders, units, average order value (AOV, revenue per order) and the online share of revenue. It must be sorted by revenue and add up to the company total.
Step 1 — Prepare a helper column
Section titled “Step 1 — Prepare a helper column”kpi_input = sales.assign( online_revenue=sales["revenue"].where(sales["channel"] == "online", 0))print(kpi_input[["region", "channel", "revenue", "online_revenue"]].head(3)) region channel revenue online_revenue0 West online 66.49 66.491 West store 14.99 0.002 South store 19.99 0.00where(condition, 0) keeps the revenue where the line is online and puts 0 elsewhere. Summing this column per region gives the online revenue. Computing it once as a column is simpler than a lambda inside agg.
Step 2 — Aggregate with named aggregation
Section titled “Step 2 — Aggregate with named aggregation”kpi = kpi_input.groupby("region").agg( revenue=("revenue", "sum"), orders=("order_id", "nunique"), units=("quantity", "sum"), online_revenue=("online_revenue", "sum"),)print(kpi) revenue orders units online_revenueregionEast 993683.72 4002 7832 426330.93North 888229.47 3612 7312 377689.94South 891766.07 3766 7495 383604.45West 822844.57 3497 6894 331841.15One agg call builds four columns from three source columns. "nunique" counts orders, not lines.
Step 3 — Add the ratio columns
Section titled “Step 3 — Add the ratio columns”kpi = kpi.assign( aov=kpi["revenue"] / kpi["orders"], online_share=kpi["online_revenue"] / kpi["revenue"],).drop(columns="online_revenue")print(kpi.sort_values("revenue", ascending=False)) revenue orders units aov online_shareregionEast 993683.72 4002 7832 248.297 0.429South 891766.07 3766 7495 236.794 0.430North 888229.47 3612 7312 245.911 0.425West 822844.57 3497 6894 235.300 0.403Ratios come after the aggregation. The AOV of a region is total revenue divided by total orders. The mean of per-order values would give the same number only if you first summed each order. East leads on revenue and AOV. The online share is between 40% and 43% in every region.
Step 4 — Check the table against the source
Section titled “Step 4 — Check the table against the source”print(round(kpi["revenue"].sum(), 2), round(sales["revenue"].sum(), 2))print(kpi["orders"].sum(), sales["order_id"].nunique())3596523.83 3596523.8314877 14877Revenue adds up. Orders add up too, because every order belongs to one store and so to one region. If an order could span two regions, the per-region nunique counts would add up to more than the company total. Checks like these catch such traps before the table reaches a slide.
Common mistakes:
- Averaging ratios:
kpi["aov"].mean()is not the company AOV. Recompute it from the totals:revenue.sum() / orders.sum(). - Counting lines as orders with
"size"or"count". Use"nunique"onorder_id. - Writing
agg({"revenue": "sum"})and then renaming. Named aggregation names the columns in the same step.
Example 2 — Spot unusual sales days per store
Section titled “Example 2 — Spot unusual sales days per store”Goal: The operations team wants each store’s unusual days, the days far above that store’s normal revenue. A big store’s ordinary Saturday must not look unusual just because the store is big.
Step 1 — Compute daily revenue per store
Section titled “Step 1 — Compute daily revenue per store”store_daily = sales.groupby(["store_id", "order_date"], as_index=False).agg( revenue=("revenue", "sum"))print(store_daily.shape)print(store_daily.head(3))(6694, 3) store_id order_date revenue0 S01 2023-01-01 1227.431 S01 2023-01-03 153.992 S01 2023-01-04 143.506,694 store-days. Not every store has orders on every one of the 731 days. as_index=False keeps store_id and order_date as columns, ready for the next step.
Step 2 — Standardize within each store
Section titled “Step 2 — Standardize within each store”by_store_rev = store_daily.groupby("store_id")["revenue"]store_daily["z"] = ( store_daily["revenue"] - by_store_rev.transform("mean")) / by_store_rev.transform("std")print(store_daily.groupby("store_id")["z"].agg(["mean", "std"]).round(3).head(3)) mean stdstore_idS01 0.0 1.0S02 0.0 1.0S03 0.0 1.0transform broadcasts each store’s mean and standard deviation to its rows. Within every store, the z-scores now have mean 0 and standard deviation 1. That is the check that the standardization worked.
Step 3 — List the most unusual days
Section titled “Step 3 — List the most unusual days”top = store_daily.nlargest(6, "z").merge(stores[["store_id", "city"]], on="store_id")print(top) store_id order_date revenue z city0 S10 2023-11-24 6983.96 8.510 Seattle1 S03 2023-08-11 5221.97 8.238 Detroit2 S09 2024-11-29 5725.67 7.970 Philadelphia3 S05 2024-09-25 5553.98 7.661 Atlanta4 S06 2024-11-02 4197.57 7.530 Miami5 S08 2024-01-11 5279.17 7.433 BostonThe list mixes promo days such as Black Friday (2023-11-24 and 2024-11-29) and days with several high-price Electronics lines (TVs and laptops). Each one is more than 7 standard deviations above its store’s mean. The merge adds the city, so the team can read the list.
Step 4 — Drop stores with a short history
Section titled “Step 4 — Drop stores with a short history”days_per_store = store_daily.groupby("store_id").size()print(days_per_store.sort_values().head(3))long_history = store_daily.groupby("store_id").filter(lambda g: len(g) >= 400)print(long_history["store_id"].nunique(), len(long_history))print(long_history.nlargest(6, "z")["store_id"].to_list())store_idS12 372S06 475S03 498dtype: int6411 6322['S10', 'S03', 'S09', 'S05', 'S06', 'S08']S12 (Denver) opened in June 2023, so it has only 372 trading days, and its mean and standard deviation are less reliable. filter drops all of S12’s rows and keeps the 11 other stores. The top six days stay the same, because none of them is in S12. In a real analysis, decide such a rule before you look at the results, so that the results cannot steer it.
Common mistakes:
- Computing the z-score with the overall mean and standard deviation. The big stores then fill the whole list.
- Using
agginstead oftransformfor the mean.aggreturns 12 rows indexed by store. Subtracting them from the 6,694 rows aligns on the index labels and gives NaN instead of z-scores. - Forgetting that a store-day with no orders is missing, not 0. The z-scores here describe days with at least one order.
Example 3 — A monthly category report for finance
Section titled “Example 3 — A monthly category report for finance”Goal: Finance wants revenue per month and category in a wide table with totals, the discount mix per category and a long version of the same numbers for their dashboard tool.
Step 1 — Build the month-by-category pivot table
Section titled “Step 1 — Build the month-by-category pivot table”sales["month"] = sales["order_date"].dt.to_period("M")monthly = sales.pivot_table( index="month", columns="category", values="revenue", aggfunc="sum", margins=True, margins_name="Total",)print(monthly.div(1000).round(1).tail(4))category Beauty Books Clothing Electronics Home Sports Totalmonth2024-10 8.9 4.2 15.8 69.7 45.4 22.2 166.12024-11 10.9 5.9 22.5 149.3 54.7 25.2 268.52024-12 12.5 9.0 26.4 173.4 53.0 28.5 302.9Total 150.4 106.9 314.7 1808.1 672.3 544.1 3596.5Each row is a month, each column a category, and the Total row and column are the margins. December 2024 is the best month at about 303 thousand USD. Electronics alone is more than half of it.
Step 2 — Compare the discount mix with crosstab
Section titled “Step 2 — Compare the discount mix with crosstab”mix = pd.crosstab(sales["category"], sales["discount"], normalize="index")print(mix.round(3))discount 0.00 0.05 0.10 0.20categoryBeauty 0.679 0.130 0.117 0.074Books 0.680 0.124 0.118 0.078Clothing 0.668 0.135 0.128 0.070Electronics 0.662 0.137 0.127 0.074Home 0.670 0.137 0.126 0.068Sports 0.696 0.116 0.122 0.066normalize="index" divides each row by its total, so each row sums to 1. All categories have about the same mix: roughly two thirds of the lines have no discount. Shares compare categories of different sizes fairly; raw counts would not.
Step 3 — Melt the report to long format
Section titled “Step 3 — Melt the report to long format”monthly_long = ( monthly.drop(index="Total", columns="Total") .reset_index() .melt(id_vars="month", var_name="category", value_name="revenue"))print(monthly_long.head(3))print(monthly_long.shape) month category revenue0 2023-01 Beauty 4404.891 2023-02 Beauty 4251.362 2023-03 Beauty 3944.87(144, 3)Drop the margins first: a dashboard sums the long rows itself and would count the totals twice. 24 months × 6 categories give 144 long rows.
Step 4 — Rebuild the wide table with pivot
Section titled “Step 4 — Rebuild the wide table with pivot”rebuilt = monthly_long.pivot(index="month", columns="category", values="revenue")original = monthly.drop(index="Total", columns="Total")print(rebuilt.shape, rebuilt.equals(original))(24, 6) TrueEach (month, category) pair appears once in the long table, so pivot works here and returns the original values. melt and pivot are exact inverses on clean data.
Common mistakes:
- Leaving out
aggfunc="sum". The default"mean"gives the average line revenue per cell, which looks plausible and is wrong for this report. - Melting a table with margins and then summing it. The total counts twice.
- Using
pivoton raw sales lines. It raisesValueError: Index contains duplicate entries.
Example 4 — Year-over-year growth per store with a MultiIndex
Section titled “Example 4 — Year-over-year growth per store with a MultiIndex”Goal: Management asks which stores grew fastest from 2023 to 2024, and how each region did. The answer must be easy to slice by region and easy to export.
Step 1 — Group by three keys
Section titled “Step 1 — Group by three keys”yearly = sales.groupby(["region", "store_id", "year"])["revenue"].sum()print(yearly.index.names, len(yearly))print(yearly.loc["West"])['region', 'store_id', 'year'] 24store_id yearS10 2023 188144.28 2024 213238.50S11 2023 127612.23 2024 141176.27S12 2023 60913.32 2024 91759.97Name: revenue, dtype: float64The result is a Series with a three-level MultiIndex. loc["West"] selects the outer level and returns the two inner levels. S12 has a small 2023, because it opened in June.
Step 2 — Compare one year across stores with xs
Section titled “Step 2 — Compare one year across stores with xs”y2024 = yearly.xs(2024, level="year")print((y2024 / 1000).round(1).sort_values(ascending=False).head(4))region store_idEast S07 263.9North S01 220.9West S10 213.2South S04 210.7Name: revenue, dtype: float64xs selects the inner year level, which loc cannot do without the outer keys. New York (S07) is the largest store in 2024.
Step 3 — Unstack the years and compute growth
Section titled “Step 3 — Unstack the years and compute growth”growth = yearly.unstack("year")growth["growth"] = growth[2024] / growth[2023] - 1print(growth.sort_values("growth", ascending=False).round(3).head(5))year 2023 2024 growthregion store_idWest S12 60913.32 91759.97 0.506South S06 84630.77 111360.45 0.316East S07 204366.16 263924.00 0.291North S01 185633.38 220899.08 0.190East S09 112222.71 132488.36 0.181unstack("year") moves the years into columns, so the growth is one vectorized division. S12 grew 50.6%, but that is mostly its first full year. S06 (Miami) grew 31.6%, the strongest like-for-like store.
Step 4 — Aggregate a level and flatten for export
Section titled “Step 4 — Aggregate a level and flatten for export”region_growth = growth.groupby(level="region")[[2023, 2024]].sum()region_growth["growth"] = region_growth[2024] / region_growth[2023] - 1print(region_growth.round(3))flat = growth.reset_index()print(flat.columns.to_list())year 2023 2024 growthregionEast 448918.63 544765.09 0.214North 410500.06 477729.41 0.164South 409501.07 482265.00 0.178West 376669.83 446174.74 0.185['region', 'store_id', 2023, 2024, 'growth']groupby(level="region") groups by an index level, with no column needed. Sum first and divide after: the growth of a region is not the mean of its stores’ growth rates. reset_index turns the levels into columns for a CSV or a plot.
Common mistakes:
- Selecting an inner level with
loc[2024]. It looks for 2024 in the outer level and raisesKeyError. Usexs(2024, level="year"). - Averaging growth rates across stores. A small store with high growth would count as much as a large one.
- Rounding before you compute. Round only the printed result.
Example 5 — Enrich sales with stores, products and customers
Section titled “Example 5 — Enrich sales with stores, products and customers”Goal: Compute gross profit per store and find out how customers with no orders differ from buyers. This needs columns from all four tables, and the joins must not duplicate rows.
Step 1 — Merge the dimension tables with validation
Section titled “Step 1 — Merge the dimension tables with validation”lines = sales.merge( stores[["store_id", "city", "size_sqm"]], on="store_id", how="left", validate="many_to_one",).merge( products[["product_id", "unit_cost"]], on="product_id", how="left", validate="many_to_one",)print(len(sales), len(lines))print(lines[["city", "unit_cost"]].isna().sum().to_list())20228 20228[0, 0]Both merges are many-to-one, so the row count stays at 20,228. No city or unit_cost is missing, so every key found a match. These two checks belong after every merge.
Step 2 — Compute gross profit per store
Section titled “Step 2 — Compute gross profit per store”lines["profit"] = lines["revenue"] - lines["unit_cost"] * lines["quantity"]profit = lines.groupby(["store_id", "city"]).agg( revenue=("revenue", "sum"), profit=("profit", "sum"), size_sqm=("size_sqm", "first"))profit["margin"] = profit["profit"] / profit["revenue"]profit["profit_per_sqm"] = profit["profit"] / profit["size_sqm"]print(profit.sort_values("profit_per_sqm", ascending=False).round(2))print(round(lines["profit"].sum(), 2)) revenue profit size_sqm margin profit_per_sqmstore_id cityS10 Seattle 401382.78 193478.18 2480 0.48 78.02S03 Detroit 213175.02 106304.62 1420 0.50 74.86S11 San Francisco 268788.50 135243.70 1890 0.50 71.56S01 Chicago 406532.46 199586.26 2850 0.49 70.03S02 Minneapolis 268521.99 132221.19 1950 0.49 67.81S09 Philadelphia 244711.07 116778.27 1760 0.48 66.35S07 New York 468290.16 224938.56 3400 0.48 66.16S08 Boston 280682.49 135181.59 2050 0.48 65.94S05 Atlanta 300259.66 148420.16 2300 0.49 64.53S04 Houston 395515.19 193537.59 3100 0.49 62.43S06 Miami 195991.22 100096.42 1680 0.51 59.58S12 Denver 152673.29 74349.29 1350 0.49 55.071760135.83city is constant within a store, so adding it to the keys only carries it along. "first" does the same for size_sqm. The total gross profit is 1,760,135.83 USD. Profit per square meter ranks the stores differently from revenue: Detroit (S03), one of the smallest stores, is second, and New York (S07), the largest, is only seventh.
Step 3 — See what validate catches
Section titled “Step 3 — See what validate catches”from pandas.errors import MergeError
store_cities = stores[["store_id", "city"]]broken = pd.concat([store_cities, store_cities.head(1)]) # S01 appears twicetry: sales.merge(broken, on="store_id", validate="many_to_one")except MergeError as err: print(type(err).__name__, "-", str(err).splitlines()[0])print(len(sales.merge(broken, on="store_id")))MergeError - Merge keys are not unique in right dataset; not a many-to-one merge22448A duplicate key in a dimension table is a common data bug. Without validate, the merge silently returns 22,448 rows instead of 20,228: S01’s 2,220 lines appear twice, and S01’s revenue doubles.
Step 4 — Find customers with no orders with indicator
Section titled “Step 4 — Find customers with no orders with indicator”orders_per_customer = sales.groupby("customer_id", as_index=False).agg( orders=("order_id", "nunique"))buyers = customers[["customer_id", "plan", "churned"]].merge( orders_per_customer, on="customer_id", how="left", indicator=True, validate="one_to_one",)print(buyers["_merge"].value_counts())print(buyers.groupby("_merge")["churned"].mean().round(3))_mergeboth 3254left_only 1746right_only 0Name: count, dtype: int64_mergeleft_only 0.270both 0.151Name: churned, dtype: float64A left merge keeps every customer. The _merge column marks the 1,746 customers with no orders as left_only. Their churn rate is 27.0%, against 15.1% for buyers. Selecting the left_only rows is an anti-join: the rows of one table with no match in the other. _merge is a categorical with three categories, so right_only shows a count of 0.
Common mistakes:
- Merging without
validateand without a row-count check. A duplicate key multiplies rows with no error. - Merging
saleswith all ofstores. Both haveregion, so you getregion_xandregion_y. Select the columns you need. - Using an inner merge to “find” unmatched rows. Inner drops them. Use
how="left", indicator=True.
Example 6 — Smooth daily revenue and detect traffic spikes
Section titled “Example 6 — Smooth daily revenue and detect traffic spikes”Goal: The marketing team wants a smooth daily revenue line, the record days, and a list of days when web visits jumped far above normal, to match them with campaigns.
Step 1 — Smooth daily revenue with a rolling mean
Section titled “Step 1 — Smooth daily revenue with a rolling mean”daily = sales.groupby("order_date")["revenue"].sum()print(len(daily), daily.index.min().date(), daily.index.max().date())ma7 = daily.rolling(7).mean()print(ma7.loc["2024-11-26":"2024-12-03"].round(1))731 2023-01-01 2024-12-31order_date2024-11-26 7716.22024-11-27 8394.62024-11-28 7710.52024-11-29 11683.42024-11-30 13030.82024-12-01 14070.12024-12-02 14919.52024-12-03 14459.1Name: revenue, dtype: float64The 7-day mean removes the weekday pattern: each window holds exactly one of each weekday. Black Friday (2024-11-29) and the following days lift the mean from about 7,700 to almost 15,000.
Step 2 — Track the record day with expanding
Section titled “Step 2 — Track the record day with expanding”record = daily.expanding().max()new_record = daily[daily == record]print(new_record.tail(4))order_date2023-08-09 11171.482023-08-11 12783.952023-11-24 31222.692024-11-29 33619.18Name: revenue, dtype: float64expanding().max() is the best day so far. Days where the revenue equals the record are the days that set a new one. The last records are the two Black Fridays.
Step 3 — Compare rolling and ewm on web visits
Section titled “Step 3 — Compare rolling and ewm on web visits”visits = web["visits"]print(visits.isna().sum())compare = pd.DataFrame( { "visits": visits, "roll7": visits.rolling(7).mean(), "roll7_min5": visits.rolling(7, min_periods=5).mean(), "ewm_hl7": visits.ewm(halflife=7).mean(), })print(compare.loc["2022-08-09":"2022-08-13"].round(0))5 visits roll7 roll7_min5 ewm_hl7date2022-08-09 4313.0 3595.0 3595.0 3473.02022-08-10 4330.0 3693.0 3693.0 3554.02022-08-11 NaN NaN 3726.0 3554.02022-08-12 3582.0 NaN 3759.0 3557.02022-08-13 3043.0 NaN 3754.0 3504.0visits has 5 blank days (tracking outages). rolling(7) gives NaN for every window that contains one, which wipes out a whole week. min_periods=5 computes the mean from the values that exist. ewm skips the missing value and keeps going.
Step 4 — Flag spikes against a trailing baseline
Section titled “Step 4 — Flag spikes against a trailing baseline”baseline = visits.rolling(28, min_periods=20).median().shift(1)spikes = web.loc[visits > 1.5 * baseline, ["visits", "marketing_spend"]]print(len(spikes))print(spikes.head(5))27 visits marketing_spenddate2022-03-14 9198.0 3307.722022-03-15 7563.0 3700.032022-03-16 6808.0 3748.662022-03-17 5749.0 3970.922022-09-06 8906.0 3349.71The baseline is the median of the previous 28 days. The median ignores earlier spikes, and shift(1) moves the window back one day, so a day is never compared with itself. 27 days pass the rule. Every one of them has a marketing spend above 3,000 USD.
Step 5 — Group the spike days into campaigns
Section titled “Step 5 — Group the spike days into campaigns”spike_dates = spikes.index.to_series()campaign_id = (spike_dates.diff().dt.days > 1).cumsum()campaigns = spikes.groupby(campaign_id.to_numpy()).agg( start=("visits", lambda s: s.index.min().date()), days=("visits", "size"), peak=("visits", "max"),)print(campaigns) start days peak0 2022-03-14 4 9198.01 2022-09-06 4 8906.02 2023-02-20 4 11230.03 2023-06-12 3 12628.04 2023-10-02 4 11208.05 2024-04-08 4 18385.06 2024-09-16 4 14446.0diff() gives the gap to the previous spike day. A gap of more than 1 day starts a new campaign, and cumsum() numbers the campaigns. The 7 campaigns of the data dictionary appear, each lasting a few days. The largest peak is 18,385 visits on 2024-04-08.
Common mistakes:
- Using
center=Trueor a window that includes the current day for a baseline. The spike then raises its own baseline. - Comparing with a rolling mean instead of a median. One huge day lifts a mean for 28 days.
- Filling the missing visits with 0. Use
min_periods,interpolate()(module 26) or a method that skips NaN.
Example 7 — Refactor a weekly report into one readable chain
Section titled “Example 7 — Refactor a weekly report into one readable chain”Goal: A colleague’s script computes the weekend share of revenue per category for 2024, using many temporary variables. Rewrite it as a method chain with .dt, .str, assign, query and pipe, and prove that the result is the same.
Step 1 — Run the original procedural code
Section titled “Step 1 — Run the original procedural code”df = sales[sales["order_date"].dt.year == 2024]df = df.copy()df["weekday"] = df["order_date"].dt.day_name()df["is_weekend"] = df["weekday"].isin(["Saturday", "Sunday"])df["weekend_revenue"] = df["revenue"] * df["is_weekend"]totals = df.groupby("category")[["revenue", "weekend_revenue"]].sum()totals["weekend_share"] = totals["weekend_revenue"] / totals["revenue"]before = totals.sort_values("weekend_share", ascending=False)print(before) revenue weekend_revenue weekend_sharecategoryBooks 57444.18 21054.03 0.367Sports 299576.31 108978.68 0.364Beauty 85444.53 30465.04 0.357Home 397844.84 140303.18 0.353Clothing 170699.61 58939.70 0.345Electronics 939924.77 319410.60 0.340The code works, but df changes meaning four times, and the .copy() is a leftover habit from older pandas. To understand one line, a reader must track every line before it.
Step 2 — Write a small function for the reusable part
Section titled “Step 2 — Write a small function for the reusable part”def add_weekend_flag(df: pd.DataFrame, date_col: str = "order_date") -> pd.DataFrame: """Add weekday and is_weekend columns from a datetime column.""" weekday = df[date_col].dt.day_name() return df.assign(weekday=weekday, is_weekend=weekday.str.startswith("S"))The function takes a DataFrame and returns a new one, so pipe can call it in a chain. Both weekend days start with S, so .str.startswith("S") builds the flag. The function never changes its input.
Step 3 — Rewrite the analysis as a chain
Section titled “Step 3 — Rewrite the analysis as a chain”after = ( sales .query("order_date.dt.year == 2024") .pipe(add_weekend_flag) .assign(weekend_revenue=lambda d: d["revenue"].where(d["is_weekend"], 0)) .groupby("category")[["revenue", "weekend_revenue"]] .sum() .assign(weekend_share=lambda d: d["weekend_revenue"] / d["revenue"]) .sort_values("weekend_share", ascending=False))print(after) revenue weekend_revenue weekend_sharecategoryBooks 57444.18 21054.03 0.367Sports 299576.31 108978.68 0.364Beauty 85444.53 30465.04 0.357Home 397844.84 140303.18 0.353Clothing 170699.61 58939.70 0.345Electronics 939924.77 319410.60 0.340Read it from the top: take sales, keep 2024, add the weekend flag, compute weekend revenue, sum per category, add the share, sort. query accepts .dt inside the expression. The lambdas in assign see the columns that earlier steps created.
Step 4 — Prove that the refactor changed nothing
Section titled “Step 4 — Prove that the refactor changed nothing”pd.testing.assert_frame_equal(before, after)print("same result:", before.equals(after))weekend_share = after["weekend_revenue"].sum() / after["revenue"].sum()print("2024 weekend share:", round(weekend_share, 3))same result: True2024 weekend share: 0.348pd.testing.assert_frame_equal raises an AssertionError with a clear message if values, dtypes or labels differ. Run it every time you refactor analysis code. Weekends are 2 of 7 days (28.6%) but bring 34.8% of the 2024 revenue.
Common mistakes:
- Writing
.assign(share=d["profit"] / d["revenue"])without the lambda.ddoes not exist outside the lambda, so you get aNameError. With a plain column of the original frame, you would silently use stale data. - Putting
print()calls or file writes insidepipefunctions. Keep chain steps free of side effects. - One chain of 30 lines. Split it at a meaningful result, such as the cleaned table, and give that a name.
Example 8 — Shrink the sales table to 40% of its memory
Section titled “Example 8 — Shrink the sales table to 40% of its memory”Goal: The sales extract will grow to many years. Cut its memory use without changing any analysis result.
Step 1 — Measure the memory per column
Section titled “Step 1 — Measure the memory per column”raw_sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])before_mem = raw_sales.memory_usage(deep=True)print(before_mem)print(f"total: {before_mem.sum() / 1e6:.2f} MB")Index 132order_id 303420order_date 161824customer_id 283192store_id 222508region 252846channel 271459product_id 242736product 559679category 301833unit_price 161824quantity 161824discount 161824revenue 161824dtype: int64total: 3.25 MBThe text columns take most of the space. product is the largest because the names are long. Each numeric or date column takes 8 bytes per row: 20,228 × 8 = 161,824 bytes.
Step 2 — Convert low-cardinality text to category
Section titled “Step 2 — Convert low-cardinality text to category”text_cols = ["store_id", "region", "channel", "product_id", "product", "category"]print(raw_sales[text_cols + ["order_id", "customer_id"]].nunique().to_list())slim = raw_sales.astype({col: "category" for col in text_cols})print(slim["region"].cat.categories.to_list())print(slim["region"].cat.codes.head(3).to_list())print(raw_sales["region"].memory_usage(deep=True))print(slim["region"].memory_usage(deep=True))[12, 4, 2, 30, 30, 6, 14877, 3254]['East', 'North', 'South', 'West'][3, 3, 2]25297820411The six columns have 2 to 30 distinct values each, so they become categories. A categorical stores each distinct text once, plus one small integer code per row (here int8, 1 byte). region shrinks from about 253 KB to 20 KB. order_id and customer_id have thousands of distinct values, so they stay str.
Step 3 — Downcast the numeric columns
Section titled “Step 3 — Downcast the numeric columns”print(raw_sales["quantity"].min(), raw_sales["quantity"].max())print(pd.Series([100, 200]).astype("int8").to_list()) # 200 does not fit in int8slim["quantity"] = pd.to_numeric(slim["quantity"], downcast="integer")slim["discount"] = slim["discount"].astype("float32")num_cols = ["quantity", "discount", "unit_price", "revenue"]print(slim[num_cols].dtypes.astype(str).to_dict())1 25[100, -56]{'quantity': 'int8', 'discount': 'float32', 'unit_price': 'float64', 'revenue': 'float64'}astype("int8") does not check the range: 200 silently wraps around to −56. pd.to_numeric(downcast="integer") checks the values first. quantity runs from 1 to 25, so it picks int8 (range −128 to 127). The discount has only 4 values (0, 0.05, 0.1 and 0.2), so float32 is enough. unit_price and revenue stay float64: they are money, and float32 keeps only about 7 significant digits.
Step 4 — Compare memory and results
Section titled “Step 4 — Compare memory and results”after_mem = slim.memory_usage(deep=True)print(f"before {before_mem.sum() / 1e6:.2f} MB, after {after_mem.sum() / 1e6:.2f} MB")print(f"ratio: {after_mem.sum() / before_mem.sum():.1%}")check_raw = raw_sales.groupby("region")["revenue"].sum()check_slim = slim.groupby("region")["revenue"].sum()print(check_raw.round(2).to_list() == check_slim.round(2).to_list())before 3.25 MB, after 1.30 MBratio: 39.9%TrueThe table now takes 39.9% of its original memory, and the regional totals are identical.
Step 5 — Set the dtypes while reading
Section titled “Step 5 — Set the dtypes while reading”dtypes = {col: "category" for col in text_cols} | {"quantity": "int8"}direct = pd.read_csv("data/sales.csv", parse_dates=["order_date"], dtype=dtypes)print(f"{direct.memory_usage(deep=True).sum() / 1e6:.2f} MB")print(direct.dtypes.astype(str).value_counts().to_dict())1.38 MB{'category': 6, 'float64': 3, 'str': 2, 'datetime64[us]': 1, 'int8': 1}read_csv(dtype=...) builds the small dtypes while it reads, so pandas does not build the full-size table first. This matters for files close to your memory limit. The result is 1.38 MB, a little more than slim, because discount stays float64 here. The dict merge operator | (module 04) joins the two dtype dicts.
Common mistakes:
- Measuring without
deep=True. Text columns then look as small as numbers, and you optimize the wrong columns. - Turning money into
float32. Totals drift by cents. Keepfloat64for amounts. - Converting a high-cardinality id to
category. The saving is small, and filters and merges on it get more awkward. - Downcasting with
astype("int8")without checking the range. Values outside −128 to 127 wrap around silently.pd.to_numeric(downcast=...)picks a safe dtype.
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
pivot_table without aggfunc |
Cells show averages instead of totals | Pass aggfunc="sum" (the default is "mean") |
pivot on data with repeated pairs |
ValueError: Index contains duplicate entries, cannot reshape |
Use pivot_table with an aggfunc |
agg result assigned as a column |
A column of NaN, because the group labels do not match the row index | Use transform to get one value per row |
| Merge on a key that is duplicated in the dimension table | More rows after the merge; totals too high | validate="many_to_one" and compare len() before and after |
| Merging two tables that share a non-key column | Columns region_x and region_y |
Select columns first, merge on both, or set suffixes |
| Inner merge to find unmatched rows | The unmatched rows are gone | how="left", indicator=True, then keep left_only |
observed=False with several categorical keys |
Many rows of zeros for impossible combinations | Keep the pandas 3 default observed=True |
loc[2024] on an inner MultiIndex level |
KeyError: 2024 |
xs(2024, level="year") or loc[pd.IndexSlice[:, :, 2024]] |
| Range slice on an unsorted MultiIndex | UnsortedIndexError |
sort_index() first |
rolling(7) on data with gaps |
A week of NaN after each missing value | min_periods= or fill the gap first |
center=True or no shift(1) in a baseline |
The baseline uses the day it should judge | Use a trailing window and shift(1) |
inplace=True inside a chain |
AttributeError: 'NoneType' object has no attribute ... |
Drop inplace; each method returns the new frame |
.dt.dayofweek |
A deprecation warning in pandas 3 | .dt.day_of_week |
memory_usage() without deep=True |
Text columns look tiny | memory_usage(deep=True) |
astype("int8") on large values |
Values wrap around silently | pd.to_numeric(s, downcast="integer") |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Web analytics and product dashboards: a backend groups page views by day and page, computes a 7-day rolling average and serves the wide table to a chart.
- Finance and accounting tools: month-by-account pivot tables with margins are the core of a trial balance.
merge(validate=...)guards the join between ledger lines and the chart of accounts. - Operations and monitoring: an alerting script compares the error count per minute with a trailing rolling median and raises an alert on a spike, the same rule as Example 6.
- Data engineering: ETL jobs concatenate daily files, join them to reference tables and set compact dtypes before they write Parquet.
Summary
Section titled “Summary”groupbysplits rows into groups.aggreturns one row per group; named aggregation (new=(column, function)) names the columns.transformreturns one value per row, for shares, ranks and z-scores within a group.filterkeeps whole groups.- In pandas 3,
observed=Trueis the default: empty categories do not appear. Passobserved=Falseonly when you want them. - Long format has one row per observation; wide format spreads a variable over columns.
pivot_table,pivot,crosstabandunstackgo to wide;meltandstackgo to long. pivot_tableaggregates (default mean; passaggfunc),pivotonly reshapes, andcrosstabcounts pairs.marginsadds totals andfill_valuefills empty cells.mergematches rows on keys. Choosehow, check the cardinality withvalidateand find unmatched rows withindicator=True.joinmerges on the index.pd.concatstacks tables.- A MultiIndex has several levels. Select with
locfrom the outside in, usexsfor an inner level andreset_indexto flatten. rolling,expandingandewmcompute moving statistics. Use trailing windows andshift(1)for baselines, andmin_periodsfor gaps..strand.dtvectorize string and date methods. Method chains withassign,queryandpiperead top to bottom and never change the input.- Measure memory with
memory_usage(deep=True). Usecategoryfor low-cardinality text, downcast integers, and keep money infloat64.
Self-check questions
Section titled “Self-check questions”Q1. What is the difference between groupby(...).agg("sum") and groupby(...).transform("sum")?
Answer
agg("sum") returns one row per group, indexed by the group keys. transform("sum") returns one value per input row, with the input index: each row gets its group’s total. Use agg for a report table and transform to add a group statistic to each row, for example to compute a share of the group total.
Q2. Write the named aggregation that gives, per category, the total revenue as revenue and the number of distinct orders as orders.
Answer
sales.groupby("category").agg(revenue=("revenue", "sum"), orders=("order_id", "nunique")). Each keyword is the new column name, and each tuple is (source column, function).
Q3. A table has a categorical column size_band with the categories small, medium and large, but no row is medium. How many rows does groupby("size_band").size() return in pandas 3? How do you get all three?
Answer
Two rows, because observed=True is the default in pandas 3 and shows only the categories that occur. groupby("size_band", observed=False).size() returns all three, with a size of 0 for medium.
Q4. Why does sales.pivot(index="region", columns="channel", values="revenue") fail, and what do you write instead?
Answer
Each (region, channel) pair appears in thousands of rows, and pivot does not aggregate, so it raises ValueError: Index contains duplicate entries, cannot reshape. Write sales.pivot_table(index="region", columns="channel", values="revenue", aggfunc="sum").
Q5. You merge sales (20,228 rows) with a stores table and get 22,448 rows. What happened, and which parameter would have caught it?
Answer
The stores table has a duplicated store_id, so every sales line of that store matched twice. validate="many_to_one" raises a MergeError as soon as the right table’s keys are not unique.
Q6. How do you list the customers who have no orders, using merge?
Answer
Left-merge the customers with a table of order counts (or with the distinct customer_id values of sales) using how="left", indicator=True. Then keep the rows where _merge == "left_only". This is an anti-join.
Q7. rev is a Series with the MultiIndex levels region, store_id and year. How do you get all 2024 values, and how do you turn the levels into columns?
Answer
rev.xs(2024, level="year") selects the inner level and drops it. rev.reset_index() turns all levels into ordinary columns. rev.loc[2024] fails, because loc looks in the outermost level first.
Q8. What is the difference between rolling(7).mean(), expanding().mean() and ewm(span=7).mean()?
Answer
rolling(7) averages the current row and the 6 rows before it. expanding() averages every row from the start to the current one. ewm(span=7) averages all rows so far with weights that shrink exponentially with age, so recent rows count most.
Q9. Why does a spike detector use visits.rolling(28).median().shift(1) and not visits.rolling(28).mean()?
Answer
The median ignores a few extreme days, so earlier spikes do not lift the baseline. shift(1) makes the baseline end on the previous day, so a spike is never part of its own baseline.
Q10. In a chain, why do you write .assign(margin=lambda d: d["profit"] / d["revenue"]) and not .assign(margin=df["profit"] / df["revenue"])?
Answer
The lambda receives the DataFrame at that point of the chain, so it sees profit and revenue as earlier steps computed them. df[...] refers to a variable outside the chain, which may not have these columns, or may have different rows.
Q11. A column channel holds two values in 20,228 rows. Which dtype saves memory, and why does it barely help for order_id?
Answer
category. It stores the two texts once and one small integer code per row. order_id has 14,877 distinct values, so the categories themselves take almost as much memory as the original text.
Q12. You receive 24 monthly CSV files with the same columns. Which tool combines them into one table, and why pass ignore_index=True?
Answer
pd.concat([pd.read_csv(path) for path in paths], ignore_index=True). concat stacks tables with the same columns; merge would match rows on keys instead. Each file has its own index starting at 0, so without ignore_index=True the result has 24 rows labeled 0, 24 labeled 1 and so on. ignore_index=True builds one fresh index from 0 to n − 1.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Exercises: 29 exercises with hints and full solutions, from warm-up to challenge.
- Mini-project: build a monthly store scorecard from four tables.
- Cheat sheet: groupby, reshaping, joins, MultiIndex, windows, accessors and memory on one page.
- Next module: 26. Data cleaning handles missing values, duplicates, type fixes, outliers and messy text in raw data.