Skip to content

25. pandas advanced — Cheat sheet

The essentials of module 25 on one page. Every runnable block on this page is checked against its output. The blocks run in order and share this setup:

import pandas as pd
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])
stores = pd.read_csv("data/stores.csv")
I want to… Use… Example
total per group groupby(key)[col].sum() sales.groupby("region")["revenue"].sum()
several named results per group named aggregation .agg(revenue=("revenue", "sum"), orders=("order_id", "nunique"))
keep the keys as columns as_index=False or .reset_index() groupby("store_id", as_index=False)
a group statistic on every row transform g["revenue"].transform("sum")
share of the group total value / transform("sum") df["rev"] / df.groupby("region")["rev"].transform("sum")
z-score within a group (x - transform("mean")) / transform("std") see GroupBy
rank within a group groupby(key)[col].rank() .rank(ascending=False)
keep groups that pass a test filter or a transform mask .filter(lambda g: len(g) >= 100)
show empty categories observed=False groupby(band, observed=False)
top n rows per group sort, then groupby().head(n) .sort_values("rev").groupby("cat").head(3)
row of the max per group idxmax + loc df.loc[df.groupby("cat")["rev"].idxmax()]
a report table with totals pivot_table(..., margins=True) aggfunc="sum", margins_name="Total"
reshape without aggregating pivot long.pivot(index="region", columns="q", values="rev")
counts of two categoricals pd.crosstab(a, b) normalize="index" for row shares
wide → long melt or stack df.melt(id_vars="store_id", var_name="q")
long → wide pivot, pivot_table or unstack s.unstack("year")
add columns from another table merge merge(stores, on="store_id", how="left", validate="many_to_one")
rows without a match indicator=True .query("_merge == 'left_only'")
join on the index join (default how="left") left.join(right_indexed)
stack files with the same columns pd.concat pd.concat(frames, ignore_index=True)
put Series side by side pd.concat(axis=1) pd.concat([a, b], axis=1, keys=["2023", "2024"])
select an inner index level xs s.xs(2024, level="year")
flatten a MultiIndex reset_index() s.reset_index()
moving average rolling(n).mean() daily.rolling(7).mean()
running total or record expanding() / cumsum() / cummax() daily.expanding().max()
smoothing that favors recent days ewm daily.ewm(span=7).mean()
a baseline that excludes today rolling(...).shift(1) v.rolling(28).median().shift(1)
text methods on a column .str s.str.contains("Pack")
date parts .dt d.dt.day_name(), d.dt.to_period("M")
a readable pipeline ( ... ) chain with assign, query, pipe see Method chaining
memory per column memory_usage(deep=True) df.memory_usage(deep=True).sum() / 1e6
shrink text columns astype("category") df.astype({"region": "category"})
shrink integers safely pd.to_numeric(downcast="integer") pd.to_numeric(df["quantity"], downcast="integer")
set small dtypes at load time read_csv(dtype=...) dtype={"region": "category", "quantity": "int8"}
prove two results are equal pd.testing.assert_frame_equal assert_frame_equal(before, after)
Method Returns Use for
g.agg(...) / g.sum(), g.mean(), … one row per group report tables
g.size() rows per group (Series) group sizes, NaN included
g.count() non-missing values per column completeness per group
g.transform(...) one value per input row shares, z-scores, group means on rows
g.filter(func) input rows of groups where func(group) is True drop small groups
g.rank(), g.cumsum(), g.cumcount() one value per row order within a group
g.shift(n), g.diff(), g.pct_change() one value per row change from the previous row of the same group
g.head(n), g.nth(k) selected input rows top rows per group
g.idxmax(), g.idxmin() index label per group the row of the extreme
g.apply(func) anything last resort; slow
g.ngroups, g.groups number of groups, dict of labels inspection
Parameter of groupby Default (pandas 3) Effect
as_index True False keeps the keys as columns
sort True False keeps the keys in order of first appearance (faster)
observed True False adds empty categories and impossible combinations
dropna True False keeps NaN as its own group
level None group by an index level: groupby(level="region")
by_cat = sales.groupby("category")
print(by_cat.agg(revenue=("revenue", "sum"), orders=("order_id", "nunique")).head(3))
cat_rev = by_cat["revenue"]
share = sales["revenue"] / cat_rev.transform("sum") # one value per row
z = (sales["revenue"] - cat_rev.transform("mean")) / cat_rev.transform("std")
print(len(share), share.groupby(sales["category"]).sum().round(6).max())
print(round(z.max(), 2))
big_baskets = by_cat.filter(lambda g: g["quantity"].mean() > 1.6) # whole groups
print(sorted(big_baskets["category"].unique()))
Output
revenue orders
category
Beauty 150417.76 2994
Books 106908.12 2491
Clothing 314686.62 3811
20228 1.0
16.91
['Beauty', 'Books', 'Clothing']
Aggregation form Column names
g["revenue"].agg(["sum", "mean"]) sum, mean
g.agg({"revenue": "sum", "quantity": "max"}) the source names
g.agg({"revenue": ["sum", "mean"]}) a two-level column MultiIndex
g.agg(total=("revenue", "sum")) total (named aggregation)
g.agg(p90=("revenue", lambda s: s.quantile(0.9))) p90; a lambda runs in Python per group
Tool Direction Aggregates Key parameters
df.pivot_table long → wide yes (default "mean") index, columns, values, aggfunc, margins, margins_name, fill_value, observed
df.pivot long → wide no; duplicates raise ValueError index, columns, values
pd.crosstab(a, b) two Series → wide counts, or values= + aggfunc= normalize="index"/"columns"/True, margins
df.melt wide → long — id_vars, value_vars, var_name, value_name
s.unstack(level) index level → columns — level (default innermost), fill_value
df.stack(level) columns → index level — keeps NaN rows in pandas 3
wide = sales.pivot_table(
index="region", columns="channel", values="revenue", aggfunc="sum", margins=True
)
print(wide.div(1000).round(1))
long = wide.drop(index="All", columns="All").reset_index().melt(
id_vars="region", var_name="channel", value_name="revenue"
)
print(long.shape, pd.crosstab(sales["region"], sales["channel"]).loc["East"].to_list())
Output
channel online store All
region
East 426.3 567.4 993.7
North 377.7 510.5 888.2
South 383.6 508.2 891.8
West 331.8 491.0 822.8
All 1519.5 2077.1 3596.5
(8, 3) [2277, 3119]
flowchart LR
    L["long: one row per observation"] -- "pivot<br/>pivot_table<br/>unstack" --> W["wide: one column per value of a key"]
    W -- "melt<br/>stack" --> L
merge parameter Values Note
how "inner" (default), "left", "right", "outer", "cross" cross pairs every row with every row
on a column or a list the key columns, same name on both sides
left_on, right_on columns keys with different names
left_index, right_index True use the index as the key
suffixes ("_x", "_y") for clashing non-key columns
validate "one_to_one", "one_to_many", "many_to_one", "many_to_many" raises MergeError when the data breaks it
indicator True or a column name adds _merge: left_only, right_only, both
df.join(other) index-based merge default how="left", unlike merge ("inner")
Relationship Example Rows after a left merge
many-to-one sales lines → stores same as the left table
one-to-one customers → order counts per customer same as the left table
one-to-many stores → sales lines grows: one row per match
many-to-many lines → lines of the same order grows fast; validate on purpose
targets = pd.DataFrame({"store_id": ["S01", "S13"], "target": [400_000, 90_000]})
m = stores[["store_id", "city"]].merge(
targets, on="store_id", how="outer", indicator=True
)
print(m["_merge"].value_counts().to_dict())
no_target = m.query("_merge == 'left_only'") # anti-join
print(len(no_target))
both = pd.concat([sales.head(2), sales.tail(2)], ignore_index=True)
print(both.index.to_list())
Output
{'left_only': 11, 'right_only': 1, 'both': 1}
11
[0, 1, 2, 3]
pd.concat parameter Effect
axis=0 (default) / axis=1 stack rows / place side by side (aligned on the index)
ignore_index=True a fresh 0..n−1 index
keys=["a", "b"] label each input; adds an outer index level (or column level with axis=1)
join="inner" keep only the columns (or index labels) common to all inputs
Task Code
create from groupby sales.groupby(["region", "store_id"])["revenue"].sum()
create from columns df.set_index(["region", "store_id"])
create from lists pd.MultiIndex.from_product([regions, years], names=["region", "year"])
outer level s.loc["North"]
full key s.loc[("North", "S01", 2024)]
any level s.xs(2024, level="year")
slice inner levels s.loc[pd.IndexSlice[:, :, 2024]] (needs sort_index())
level values s.index.get_level_values("year")
aggregate a level s.groupby(level="region").sum()
reorder or drop levels s.reorder_levels([...]), s.droplevel("year")
to columns s.reset_index()
rev = sales.assign(year=sales["order_date"].dt.year).groupby(
["region", "store_id", "year"]
)["revenue"].sum()
print(rev.index.names, rev.loc[("North", "S01", 2024)].round(2))
print(rev.loc[pd.IndexSlice[:, ["S01", "S02"], 2024]].round(0).to_list()) # needs sort
grid = pd.MultiIndex.from_product(
[["S01", "S12"], [2022, 2023]], names=["store_id", "year"]
) # every combination; missing ones become 0 below
print(rev.droplevel("region").reindex(grid, fill_value=0).round(0).to_list())
print(rev.xs(2024, level="year").groupby(level="region").sum().round(0).to_dict())
Output
['region', 'store_id', 'year'] 220899.08
[220899.0, 141644.0]
[0.0, 185633.0, 0.0, 60913.0]
{'East': 544765.0, 'North': 477729.0, 'South': 482265.0, 'West': 446175.0}
Call Window Note
rolling(7) current row and 6 before first 6 rows NaN; min_periods= lowers that
rolling(7, center=True) 3 before, current, 3 after uses future values; not for forecasts
rolling("7D") the last 7 days of a DatetimeIndex robust to missing dates
expanding() from the first row to the current row running totals, records
ewm(span=7) all rows, weights shrink by 1−α1 - \alpha per row α=2/(span+1)\alpha = 2 / (\text{span} + 1)
ewm(halflife=7) / ewm(alpha=0.25) / ewm(com=3) same, other ways to set α\alpha pass exactly one of them
groupby(key)[col].transform(lambda s: s.rolling(3).mean()) per group sort by time within each group first

Common follow-ups: .mean(), .sum(), .median(), .std(), .min(), .max(), .quantile(0.9), .count().

daily = sales.groupby("order_date")["revenue"].sum()
smooth = pd.DataFrame(
{
"ma7": daily.rolling(7).mean(),
"record": daily.cummax(),
"ewm7": daily.ewm(span=7).mean(),
}
)
print(smooth.tail(3).round(1))
Output
ma7 record ewm7
order_date
2024-12-29 7225.9 33619.2 8447.7
2024-12-30 8382.8 33619.2 10019.3
2024-12-31 8609.7 33619.2 9504.8
.str method Does
lower(), upper(), title(), strip() case and whitespace
contains(pat, case=False, regex=True) boolean mask
startswith(s), endswith(s) boolean mask
replace(pat, repl, regex=False) substitute text
split(sep, n=1, expand=True) split into columns
extract(r"(\d+)-(\w+)") one column per capturing group
len(), str[a:b], zfill(n), pad(n) length, slicing, padding
cat(sep="-") join all values (or with others=)
.dt attribute or method Gives
year, quarter, month, day numbers
day_of_week (Monday = 0), day_name(), month_name() weekday and month
is_month_end, is_month_start, days_in_month calendar facts
to_period("M") / ("Q") / ("W") a period label for grouping
isocalendar() a frame with ISO year, week, day
strftime("%Y-%m") text labels
floor("D"), normalize() drop the time part
names = pd.Series(["Running Socks 3-Pack", "55-inch 4K Smart TV", " Yoga Mat "])
print(names.str.strip().str.lower().to_list())
print(names.str.extract(r"(\d+)-(inch|Pack)").fillna("-").to_numpy().tolist())
d = sales["order_date"].head(2)
print(d.dt.day_name().to_list(), d.dt.to_period("Q").astype(str).to_list())
Output
['running socks 3-pack', '55-inch 4k smart tv', 'yoga mat']
[['3', 'Pack'], ['55', 'inch'], ['-', '-']]
['Sunday', 'Sunday'] ['2023Q1', '2023Q1']
Method In a chain
assign(new=lambda d: ...) add or replace columns; the lambda sees the current frame
query("a > 1 and b == 'x'") filter rows; @var for Python variables, .dt and .str allowed
pipe(func, *args, **kwargs) call your own func(df, ...)
loc[lambda d: d["x"] > 0] filter with a lambda
rename(columns=...), astype({...}) rename, change dtypes
sort_values, head, nlargest order and trim
def add_weekday(df: pd.DataFrame) -> pd.DataFrame:
return df.assign(weekday=df["order_date"].dt.day_name())
top_days = (
sales
.query("category == 'Books' and order_date.dt.year == 2024") # filter
.pipe(add_weekday) # own step
.groupby("weekday")
.agg(revenue=("revenue", "sum"))
.assign(share=lambda d: d["revenue"] / d["revenue"].sum()) # derived column
.nlargest(2, "share")
)
print(top_days)
Output
revenue share
weekday
Saturday 11544.66 0.201
Sunday 9509.37 0.166
dtype Bytes per value Range or note
int8 / int16 / int32 / int64 1 / 2 / 4 / 8 −128..127 / −32,768..32,767 / ±2.1 billion / huge
float32 / float64 4 / 8 ~7 / ~16 significant digits
datetime64[us] 8 pandas 3 default unit from read_csv
category 1–2 per row + the categories once for low-cardinality text
str (pandas 3) text length plus overhead ids, free text
before = sales.memory_usage(deep=True).sum()
slim = sales.astype({c: "category" for c in ["region", "channel", "category"]})
slim["quantity"] = pd.to_numeric(slim["quantity"], downcast="integer")
after = slim.memory_usage(deep=True).sum()
print(f"{before / 1e6:.2f} MB -> {after / 1e6:.2f} MB", slim["quantity"].dtype)
Output
3.25 MB -> 2.34 MB int8
  • pivot_table averages by default. Always pass aggfunc.
  • pivot never aggregates. Duplicate (index, column) pairs raise ValueError: Index contains duplicate entries, cannot reshape.
  • agg returns one row per group; assigning it as a column gives NaN, because the group labels do not match the row index. Use transform.
  • "size" counts rows; "count" counts non-missing values; "nunique" counts distinct values. Orders are ("order_id", "nunique"), not "size".
  • A mean of group means is not the overall mean, and the mean of growth rates is not the total growth. Recompute ratios from totals.
  • pandas 3 defaults to observed=True. Code from pandas 2 that relied on empty categories needs observed=False.
  • A merge on a duplicated key multiplies rows silently. Use validate= and compare len() before and after.
  • Shared non-key columns get _x and _y. Select columns or set suffixes.
  • Merge keys should have the same dtype. A category key and a str key still match, but the key column of the result can come out as object. Cast both sides to the same dtype first.
  • loc on a MultiIndex starts at the outermost level. Use xs(..., level=...) for inner levels, and sort_index() before range slices.
  • rolling(n) returns NaN until it has n values and for every window that holds a NaN. Set min_periods.
  • Baselines must not see the value they judge: trailing window plus shift(1), never center=True.
  • rolling(7) counts rows; rolling("7D") counts days. They differ when dates are missing.
  • .dt.dayofweek, .dt.weekofyear and similar old names are deprecated or gone. Use .dt.day_of_week and .dt.isocalendar().week.
  • In assign, use a lambda to refer to columns made earlier in the chain.
  • astype("int8") wraps out-of-range values silently. pd.to_numeric(downcast="integer") checks the range.
  • Keep money in float64; float32 keeps only about 7 significant digits.