pandas
pandas gives Python labeled tables (DataFrame) and labeled columns (Series). This page is a reference for pandas 3.x: input and output, selection, dtypes, groupby, reshaping, joins, time series, text, cleaning, and the pandas 3 rules (copy-on-write, the str dtype, removed APIs). Every block runs in order and shares the setup below.
import numpy as npimport pandas as pd
pd.set_option("display.width", 100) # wrap printed tables at 100 characterspd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])df = pd.DataFrame( { "store": ["S01", "S02", "S01", "S03", "S02", "S01"], "region": ["North", "South", "North", "West", "South", "North"], "month": pd.to_datetime(["2024-01-31", "2024-01-31", "2024-02-29", "2024-02-29", "2024-03-31", "2024-03-31"]), "units": [12, 7, 15, 4, 9, 11], "revenue": [1200.0, 650.0, 1480.0, np.nan, 905.0, 1010.0], }, index=pd.Index(["a", "b", "c", "d", "e", "f"], name="id"),)Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| read a CSV with dates | pd.read_csv(path, parse_dates=[...]) |
pd.read_csv("data/sales.csv", parse_dates=["order_date"]) |
| read only some columns and rows | usecols=, nrows= |
usecols=["order_date", "revenue"] |
| read Parquet / Excel / JSON | pd.read_parquet, pd.read_excel, pd.read_json |
pd.read_excel(path, sheet_name="sales") |
| flatten nested JSON | pd.json_normalize(records, record_path=, meta=) |
one row per nested item |
| write a file without the index | to_csv(path, index=False) |
df.to_parquet("output/x.parquet") |
| see size, dtypes and gaps | df.shape, df.dtypes, df.info() |
df.isna().sum() |
| summary statistics | df.describe() |
describe(include="str") for text |
| count values | s.value_counts(normalize=True, dropna=False) |
shares with NaN counted |
| pick columns | df[["a", "b"]] |
|
| pick rows and columns by label | df.loc[rows, cols] |
df.loc["b":"d", ["units"]] (end included) |
| pick by position | df.iloc[rows, cols] |
df.iloc[:3, -1] (end excluded) |
| one cell, fast | df.at[label, col], df.iat[i, j] |
df.at["c", "units"] |
| filter rows | a boolean mask | df[(df["units"] > 8) & (df["region"] != "West")] |
| filter with an expression | df.query("...") |
df.query("units > @k and region == 'North'") |
| test membership or a range | s.isin(list), s.between(lo, hi) |
s.isin(["North", "East"]) |
| sort by several columns | sort_values([a, b], ascending=[True, False]) |
add a tie-breaker column |
| top n rows | df.nlargest(n, col) |
sales.nlargest(5, "revenue") |
| add a column | df["new"] = expr or df.assign(new=...) |
assign(k=lambda d: d["revenue"] / 1000) |
| if/else and if/elif/else | np.where, np.select |
np.where(s > 0, "up", "down") |
| set values in some rows | df.loc[mask, col] = value |
never df[col][mask] = value |
| look up values from a dict | s.map(mapping) |
missing keys → NaN |
| bin numbers into labels | pd.cut(s, bins, labels=...), pd.qcut(s, q) |
pd.cut(age, [0, 30, 60, 120]) |
| convert text to numbers / dates | pd.to_numeric(errors="coerce"), pd.to_datetime(format=...) |
bad values → NaN / NaT |
| use an ordered category | pd.CategoricalDtype(cats, ordered=True) |
["basic", "standard", "premium"] |
| aggregate per group | groupby(key).agg(name=(col, func)) |
agg(total=("revenue", "sum")) |
| a group value on every row | groupby(key)[col].transform(func) |
share of group total |
| keep groups that pass a test | groupby(key).filter(func) |
filter(lambda g: len(g) >= 2) |
| wide report table | pivot_table(index, columns, values, aggfunc) |
always pass aggfunc |
| wide → long | df.melt(id_vars=..., var_name=..., value_name=...) |
|
| join two tables | merge(other, on=key, how="left", validate="many_to_one") |
indicator=True to audit |
| stack tables with the same columns | pd.concat(frames, ignore_index=True) |
|
| date parts | .dt.year, .dt.month, .dt.day_of_week, .dt.to_period("M") |
|
| totals per month | resample("ME", on=col) or groupby(pd.Grouper(key=col, freq="ME")) |
|
| moving average | s.rolling(7).mean() |
rolling("7D") on a date index |
| change from the previous row | s.diff(), s.pct_change(), s.shift(1) |
per group: groupby(k)[c].shift() |
| text methods | .str.lower(), .str.contains(), .str.extract() |
|
| fill or drop gaps | fillna(value), ffill(), interpolate(), dropna(subset=[...]) |
per group with groupby |
| find and drop duplicates | duplicated(subset, keep=False), drop_duplicates(subset, keep="last") |
|
| select from a MultiIndex | df.loc[(k1, k2)], df.xs(k2, level="name") |
sort_index() first |
| flatten two-level column names | ["_".join(c) for c in df.columns.to_flat_index()] |
after agg({"c": [...]}) |
| compare two frames in a test | pd.testing.assert_frame_equal(a, b) |
checks dtypes too |
Read and write
Section titled “Read and write”| Format | Read | Write | Keeps dtypes | Needs |
|---|---|---|---|---|
| CSV | pd.read_csv(path) |
df.to_csv(path, index=False) |
no: dates and categories come back as str |
— |
| Parquet | pd.read_parquet(path, columns=[...]) |
df.to_parquet(path, index=False) |
yes | pyarrow |
| Excel | pd.read_excel(path, sheet_name=...) |
df.to_excel(path, sheet_name=..., index=False) |
numbers, dates | openpyxl |
| JSON records | pd.read_json(path) |
df.to_json(path, orient="records", date_format="iso") |
partly | — |
| JSON lines | pd.read_json(path, lines=True) |
df.to_json(path, orient="records", lines=True) |
partly | — |
| nested JSON | pd.json_normalize(data, record_path=, meta=) |
— | partly | — |
| SQL | pd.read_sql(query, conn, params=...) |
df.to_sql(name, conn, index=False) |
partly | a DB driver |
| clipboard, HTML | pd.read_clipboard(), pd.read_html(io.StringIO(html)) |
df.to_markdown(), df.to_html() |
no | lxml, tabulate |
read_csv option |
Does |
|---|---|
usecols=[...] |
load only these columns |
parse_dates=[...] |
parse these columns as dates (date_format= for one fixed format) |
dtype={"col": "category"} |
set dtypes at load: "category", "int32", "Int64", "str" |
index_col="col" |
use a column as the index |
na_values=["-", "?"] |
extra missing-value tokens |
keep_default_na=False |
stop reading NA, None, null and "" as missing |
nrows=1000, skiprows=, chunksize= |
read part of a file, or in pieces |
sep=";", decimal=",", thousands="." |
European number formats |
encoding="latin-1" |
non-UTF-8 files |
dtype_backend="pyarrow" |
Arrow dtypes for every column |
from pathlib import Path
Path("output").mkdir(exist_ok=True) # never write into data/part = pd.read_parquet("data/sales_sample.parquet", columns=["order_date", "revenue"])part.to_csv("output/part.csv", index=False)back = pd.read_csv("output/part.csv")print(part.dtypes.astype(str).to_dict())print(back.dtypes.astype(str).to_dict()) # the date is text againprint(part.head(1).to_json(orient="records", date_format="iso")){'order_date': 'datetime64[us]', 'revenue': 'float64'}{'order_date': 'str', 'revenue': 'float64'}[{"order_date":"2023-01-01T00:00:00.000","revenue":66.49}]import json
with open("data/customers.json", encoding="utf-8") as f: export = json.load(f)flat = pd.json_normalize(export["customers"], sep="_") # nested keys -> columnsorders = pd.json_normalize(export["customers"], record_path="orders", meta=["customer_id"]) # one row per orderprint(flat.shape, [c for c in flat.columns if c.startswith("address_")][:2])print(orders.columns.to_list(), len(orders))(20, 12) ['address_street', 'address_city']['order_id', 'date', 'items', 'amount', 'customer_id'] 48Inspect
Section titled “Inspect”| Call | Shows |
|---|---|
df.head(n), df.tail(n), df.sample(n, random_state=42) |
some rows |
df.shape, len(df), df.columns, df.index |
size and labels |
df.dtypes, df.info() |
dtypes; info() prints by itself and returns None |
df.describe(), df.describe(include="str") |
numeric summary; text summary |
s.value_counts(), s.nunique(), s.unique() |
counts, number of distinct values, distinct values |
df.isna().sum(), df.isna().mean() |
gaps per column, share of gaps |
df.memory_usage(deep=True) |
bytes per column, text included |
df.corr(numeric_only=True) |
correlations of numeric columns |
print(sales.shape, sales["region"].value_counts().to_dict())print(sales["channel"].value_counts(normalize=True).round(3).to_dict())print(df.isna().sum().to_dict(), df["store"].nunique())print(sales[["unit_price", "quantity"]].describe().loc[["mean", "50%", "max"]])(20228, 13) {'East': 5396, 'South': 5144, 'North': 4966, 'West': 4722}{'store': 0.58, 'online': 0.42}{'store': 0, 'region': 0, 'month': 0, 'units': 0, 'revenue': 1} 3 unit_price quantitymean 146.333 1.4650% 69.990 1.00max 1299.000 25.00Select and filter
Section titled “Select and filter”| Syntax | Selects by | Returns | Slice end |
|---|---|---|---|
df["col"] |
one column name | Series | — |
df[["a", "b"]] |
column names | DataFrame | — |
df[mask] |
a boolean Series | DataFrame | — |
df.loc["b":"d", "units":"revenue"] |
labels | DataFrame | included |
df.loc[mask, ["units"]] |
mask + labels | DataFrame | — |
df.loc[lambda d: d["units"] > 8] |
a function of the frame | DataFrame | — |
df.iloc[0:3, [0, -1]] |
positions | DataFrame | excluded |
df.at["c", "units"], df.iat[2, 3] |
one cell | scalar | — |
df.query("units > @k and region == 'North'") |
an expression string | DataFrame | — |
df.filter(like="rev"), df.select_dtypes("number") |
column names, dtypes | DataFrame | — |
s.iloc[0], s.loc["a"] |
one value | scalar | — |
print(df.loc["b":"d", ["store", "units"]])print(df.iloc[-2:, [0, 3]].index.to_list(), df.at["c", "units"], df.iat[2, 3])k = 8mask = (df["units"] > k) & df["region"].isin(["North", "South"])print(df.index[mask].to_list())print(df.query("units > @k and store != 'S02'").index.to_list()) # @k: a variableprint(df[df["month"].between("2024-02-01", "2024-03-31")].index.to_list())print(df.select_dtypes("number").columns.to_list())print(df.filter(like="re").columns.to_list()) # names that contain "re" store unitsidb S02 7c S01 15d S03 4['e', 'f'] 15 15['a', 'c', 'e', 'f']['a', 'c', 'f']['c', 'd', 'e', 'f']['units', 'revenue']['store', 'region', 'revenue']| Need | Write |
|---|---|
| and / or / not | (a) & (b), (a) | (b), ~(a); never and, or, not |
| one of several values | s.isin(["x", "y"]) |
| a range | s.between(lo, hi); inclusive="left" for lo <= s < hi |
| missing / present | s.isna(), s.notna() |
| text pattern | s.str.contains("pack", case=False) |
| count / share of matches | mask.sum(), mask.mean() |
dtypes in pandas 3
Section titled “dtypes in pandas 3”| dtype | Missing marker | Use |
|---|---|---|
int64, float64, bool |
NaN for float only |
NumPy dtypes; a gap turns int64 into float64 |
str |
NaN |
default for text in pandas 3 (Arrow-backed, StringDtype(na_value=nan)) |
string |
pd.NA |
the nullable string dtype, opt-in |
Int64, Float64, boolean |
pd.NA |
nullable numbers and flags (capital letter) |
category |
NaN |
few distinct, repeated values; ordered if you need < |
datetime64[us], timedelta64[us] |
NaT |
pandas 3 default unit is microseconds |
period[M] |
NaT |
calendar periods (months, quarters) |
object |
None, NaN |
lists, dicts, mixed Python objects |
int64[pyarrow] and friends |
<NA> |
with dtype_backend="pyarrow" |
names = pd.Series(["ana", None, "Bo"])print(names.dtype, names.dtype == "str", names.isna().tolist())print(names.str.upper().to_list())print(pd.Series([3, None]).dtype, pd.Series([3, None], dtype="Int64").to_list())print(df.convert_dtypes().dtypes.astype(str).to_list()) # whole floats -> Int64raw = pd.Series(["79.99", "1,299.00", "n/a"])print(pd.to_numeric(raw.str.replace(",", ""), errors="coerce").to_list())print(pd.to_datetime(pd.Series(["31/12/2024"]), format="%d/%m/%Y").dt.date.to_list())str True [False, True, False]['ANA', nan, 'BO']float64 [3, <NA>]['string', 'string', 'datetime64[us]', 'Int64', 'Int64'][79.99, 1299.0, nan][datetime.date(2024, 12, 31)]plan = pd.Series(["basic", "premium", "standard", "basic"])levels = pd.CategoricalDtype(["basic", "standard", "premium"], ordered=True)plan = plan.astype(levels)print(plan.cat.codes.to_list(), (plan >= "standard").to_list(), plan.max())print(plan.value_counts(sort=False).to_dict()) # counts in category orderas_str = sales["region"].memory_usage(deep=True)as_cat = sales["region"].astype("category").memory_usage(deep=True)print(as_cat < as_str, round(as_str / as_cat, 1)) # category saves memory[0, 2, 1, 0] [False, True, True, False] premium{'basic': 2, 'standard': 1, 'premium': 1}True 12.4| Convert with | On a bad value |
|---|---|
s.astype("float64"), df.astype({"a": "int32"}) |
raises ValueError |
pd.to_numeric(s, errors="coerce") |
NaN |
pd.to_numeric(s, downcast="integer") |
the smallest integer dtype that fits |
pd.to_datetime(s, format="%Y-%m-%d", errors="coerce") |
NaT |
df.convert_dtypes() |
nullable dtypes for every column |
s.astype("category"), s.cat.codes |
categories, integer codes |
New columns
Section titled “New columns”out = df.assign( price=lambda d: d["revenue"] / d["units"], # vectorized math size=lambda d: np.where(d["units"] >= 10, "big", "small"), # if/else band=lambda d: pd.cut(d["units"], [0, 5, 10, 20], labels=["low", "mid", "high"]), city=lambda d: d["store"].map({"S01": "Chicago", "S02": "Dallas"}), # lookup)print(out[["units", "price", "size", "band", "city"]])df2 = df.copy()df2["flag"] = False # default first ...df2.loc[df2["units"] > 10, "flag"] = True # ... then some rowsprint(df2["flag"].to_list()) units price size band cityida 12 100.000 big high Chicagob 7 92.857 small mid Dallasc 15 98.667 big high Chicagod 4 NaN small low NaNe 9 100.556 small mid Dallasf 11 91.818 big high Chicago[True, False, True, False, False, True]| Task | Fast | Slow (one Python call per row) |
|---|---|---|
| arithmetic on columns | df["a"] * df["b"] |
df.apply(lambda r: r["a"] * r["b"], axis=1) |
| if/else | np.where(cond, x, y), s.where(cond, other) |
s.apply(lambda v: x if v > 0 else y) |
| several branches | np.select(conds, choices, default) |
a row function with if/elif |
| code → label | s.map(dict_or_series) |
s.apply(lambda v: mapping[v]) |
| numbers → bins | pd.cut, pd.qcut |
a loop of if tests |
| element-wise on every cell | df.map(func) |
— (applymap was removed) |
Missing values
Section titled “Missing values”| Call | Does |
|---|---|
s.isna(), s.notna(), pd.isna(x) |
find gaps (NaN, None, NaT, pd.NA) |
df.dropna(subset=["a"]), dropna(thresh=k) |
drop rows with gaps in a / with fewer than k values |
s.fillna(0), s.fillna(s.median()) |
fill with a constant or a statistic |
df.fillna({"a": 0, "b": "unknown"}) |
one fill value per column |
s.fillna(df.groupby(k)[c].transform("median")) |
fill with the group median |
s.ffill(), s.bfill(), groupby(k)[c].ffill() |
repeat the last / next known value |
s.interpolate(), interpolate(method="time") |
straight line between known values |
s.sum(), s.mean() |
skip NaN by default; skipna=False to propagate it |
df[c + "_missing"] = df[c].isna() |
remember what you filled (do it before the fill) |
r = df["revenue"]print(r.isna().sum(), r.count(), r.mean().round(1), r.mean(skipna=False))print(r.fillna(r.groupby(df["region"]).transform("median")).to_list())print(r.ffill().to_list(), r.interpolate().to_list())print(len(df.dropna(subset=["revenue"])), df.fillna({"revenue": 0})["revenue"].sum())1 5 1049.0 nan[1200.0, 650.0, 1480.0, nan, 905.0, 1010.0][1200.0, 650.0, 1480.0, 1480.0, 905.0, 1010.0] [1200.0, 650.0, 1480.0, 1192.5, 905.0, 1010.0]5 5245.0read_csv reads "", NA, N/A, NULL, null, NaN, nan, None and #N/A as missing by default. It does not read -, ?, unknown, 0 or 999 as missing: pass na_values=.
Duplicates
Section titled “Duplicates”log = pd.DataFrame({"order": ["O1", "O1", "O2", "O3", "O3"], "version": [1, 1, 1, 1, 2], "qty": [2, 2, 5, 1, 3]})print(log.duplicated().sum(), log.duplicated(subset="order", keep=False).to_list())latest = log.sort_values(["order", "version"]).drop_duplicates("order", keep="last")print(latest.to_dict("list"))print(log.loc[log.groupby("order")["version"].idxmax(), "qty"].to_list())1 [True, True, False, True, True]{'order': ['O1', 'O2', 'O3'], 'version': [1, 1, 2], 'qty': [2, 5, 3]}[2, 5, 3]| Call | Marks or keeps |
|---|---|
df.duplicated() |
rows equal to an earlier row in every column |
df.duplicated(subset=key) |
rows whose key appeared before |
keep="first" / "last" / False |
leave the first / last copy unmarked / mark every copy |
df.drop_duplicates(subset=key, keep="last") |
one row per key, the last in table order |
df.loc[df.groupby(key)[t].idxmax()] |
one row per key, the latest by t |
GroupBy
Section titled “GroupBy”by_region = df.groupby("region")print(by_region.agg(total=("revenue", "sum"), orders=("store", "size"), stores=("store", "nunique"), best=("units", "max")))share = df["units"] / by_region["units"].transform("sum") # one value per rowprint(share.round(2).to_list())print(by_region.filter(lambda g: len(g) >= 2).index.to_list())print(df.groupby("store", as_index=False)["units"].sum().to_dict("list"))print(by_region["units"].rank(ascending=False).to_list(), by_region.size().to_dict()) total orders stores bestregionNorth 3690.0 3 1 15South 1555.0 2 1 9West 0.0 1 1 4[0.32, 0.44, 0.39, 1.0, 0.56, 0.29]['a', 'b', 'c', 'e', 'f']{'store': ['S01', 'S02', 'S03'], 'units': [38, 16, 4]}[2.0, 2.0, 1.0, 1.0, 1.0, 3.0] {'North': 3, 'South': 2, 'West': 1}| Method | Returns | Use for |
|---|---|---|
g.agg(...), g.sum(), g.mean() |
one row per group | report tables |
g.size() / g.count() |
rows per group / non-missing values per column | sizes, completeness |
g.sum(min_count=1) |
NaN for a group with no values |
the default gives 0.0 (West above) |
g.transform(func) |
one value per input row | shares, z-scores, group fills |
g.filter(func) |
the 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 within each group |
g.head(n), g.nth(k), g.idxmax() |
some input rows or labels | top rows per group |
g.apply(func) |
anything | last resort: slow; the group keys are not passed to func |
| Aggregation form | Result columns |
|---|---|
g["revenue"].agg(["sum", "mean"]) |
sum, mean |
g.agg({"revenue": "sum", "units": "max"}) |
the source names |
g.agg(total=("revenue", "sum")) |
total (named aggregation, preferred) |
g.agg(p90=("revenue", lambda s: s.quantile(0.9))) |
p90 (a lambda runs in Python per group) |
groupby parameter |
pandas 3 default | Effect |
|---|---|---|
as_index |
True |
False keeps the keys as columns |
sort |
True |
False keeps first-appearance order (faster) |
observed |
True |
False adds empty categories |
dropna |
True |
False keeps a NaN key as its own group |
Reshape
Section titled “Reshape”| Tool | Direction | Aggregates | Key arguments |
|---|---|---|---|
df.pivot_table |
long → wide | yes (default "mean") |
index, columns, values, aggfunc, margins, fill_value |
df.pivot |
long → wide | no; duplicate pairs raise ValueError |
index, columns, values |
pd.crosstab(a, b) |
two columns → counts | counts or values= + aggfunc= |
normalize="index", margins=True |
df.melt |
wide → long | — | id_vars, value_vars, var_name, value_name |
s.unstack(level) |
index level → columns | — | fill_value |
df.stack() |
columns → index level | — | keeps NaN cells in pandas 3 |
df.explode(col) |
list cells → rows | — | ignore_index=True |
wide = df.assign(month=df["month"].dt.month).pivot_table( index="region", columns="month", values="units", aggfunc="sum", fill_value=0, margins=True, margins_name="Total")print(wide)long = wide.drop(index="Total", columns="Total").reset_index().melt( id_vars="region", var_name="month", value_name="units")print(long.shape, long.query("units > 0")["units"].sum())print(pd.crosstab(df["region"], df["store"]))print(df.set_index(["region", "store"])["units"].groupby(level=0).sum().to_dict())month 1 2 3 TotalregionNorth 12 15 11 38South 7 0 9 16West 0 4 0 4Total 19 19 20 58(9, 3) 58store S01 S02 S03regionNorth 3 0 0South 0 2 0West 0 0 1{'North': 38, 'South': 16, 'West': 4}MultiIndex
Section titled “MultiIndex”A MultiIndex has several key levels. It comes out of groupby([k1, k2]), pivot_table, set_index([...]) and agg({"c": ["sum", "max"]}) (on the columns).
| Task | Code |
|---|---|
| make one from columns | df.set_index(["region", "store"]) |
| make every combination | pd.MultiIndex.from_product([regions, years], names=["region", "year"]) |
| sort it (needed before slices) | mi = mi.sort_index() |
| select by the outer level / a full key | mi.loc["North"], mi.loc[("North", "S01")] |
| select by an inner level | mi.xs("S01", level="store") |
| slice several levels | mi.loc[pd.IndexSlice[:, ["S01", "S03"]], :] |
| aggregate one level | mi.groupby(level="region").sum() |
| drop or swap levels | mi.droplevel("region"), mi.swaplevel() |
| levels back to columns | mi.reset_index() |
| flatten two-level column names | df.columns = ["_".join(c) for c in df.columns.to_flat_index()] |
mi = df.groupby(["region", "store"])[["units", "revenue"]].sum().sort_index()print(mi.index.names, mi.loc[("North", "S01"), "units"])print(mi.xs("S02", level="store")["units"].to_dict())print(mi.loc[pd.IndexSlice[:, ["S01", "S03"]], "units"].to_list())two = df.groupby("region").agg({"units": ["sum", "max"]}) # two-level columnsprint(two.columns.to_list())two.columns = ["_".join(c) for c in two.columns.to_flat_index()]print(two)['region', 'store'] 38{'South': 16}[38, 4][('units', 'sum'), ('units', 'max')] units_sum units_maxregionNorth 38 15South 16 9West 4 4flowchart LR
L["long: one row per observation"] -- "pivot<br/>pivot_table<br/>unstack" --> W["wide: one column per key value"]
W -- "melt<br/>stack" --> L
Merge, join and concat
Section titled “Merge, join and concat”merge argument |
Values | Note |
|---|---|---|
how |
"inner" (default), "left", "right", "outer", "cross" |
cross: every pair of rows |
on / left_on, right_on |
key columns | same name / different names |
left_index, right_index |
True |
use the index as the key |
validate |
"one_to_one", "one_to_many", "many_to_one", "many_to_many" |
raises MergeError when the data breaks it |
indicator |
True |
adds _merge: left_only, right_only, both |
suffixes |
("_x", "_y") |
for clashing non-key columns |
| Tool | Joins on | Default how |
|---|---|---|
left.merge(right, on=key) |
columns | "inner" |
left.join(right) |
the index of right |
"left" |
pd.concat(frames) |
stacks rows (axis=0) or columns (axis=1, aligned on the index) |
outer union of columns |
pd.merge_asof(left, right, on=t, by=k) |
the nearest earlier key (both sorted) | direction="backward" |
stores = pd.DataFrame({"store": ["S01", "S02", "S04"], "city": ["Chicago", "Dallas", "Miami"]})m = df.merge(stores, on="store", how="left", validate="many_to_one", indicator=True)print(m["_merge"].value_counts().to_dict(), len(df), len(m))audit = df[["store"]].drop_duplicates().merge(stores, how="outer", indicator=True)print(audit[["store", "_merge"]].to_dict("list"))print(pd.concat([df.head(2), df.tail(1)], ignore_index=True).index.to_list())print(pd.concat([df["units"], df["revenue"]], axis=1, keys=["u", "r"]).shape){'both': 5, 'left_only': 1, 'right_only': 0} 6 6{'store': ['S01', 'S02', 'S03', 'S04'], '_merge': ['both', 'both', 'left_only', 'right_only']}[0, 1, 2](6, 2)dupes = pd.DataFrame({"store": ["S01", "S01"], "city": ["Chicago", "Evanston"]})bad = df.merge(dupes, on="store", how="left", validate="many_to_one")pandas.errors.MergeError: Merge keys are not unique in right dataset; not a many-to-one merge| Relationship | Example | Rows after a left merge |
|---|---|---|
| many-to-one | order lines → stores | the same as the left table |
| one-to-one | customers → their profile | the same as the left table |
| one-to-many | stores → order lines | grows: one row per match |
| many-to-many | lines → lines of the same order | grows fast; validate on purpose |
Time series
Section titled “Time series”.dt accessor |
Gives |
|---|---|
year, quarter, month, day, hour |
numbers |
day_of_week (Monday = 0), day_name(), month_name() |
weekday and month |
is_month_end, days_in_month, day_of_year |
calendar facts |
isocalendar().week |
ISO week number |
to_period("M"), to_period("Q") |
period labels for grouping |
strftime("%Y-%m") |
text labels |
floor("D"), normalize(), tz_localize("UTC"), tz_convert(...) |
drop the time, time zones |
| Frequency alias | Means |
|---|---|
"D", "B", "W" ("W-MON") |
day, business day, week ending Sunday (or Monday) |
"ME", "MS" |
month end, month start |
"QE", "QS", "YE", "YS" |
quarter and year, end or start |
"h", "min", "s", "ms" |
hour, minute, second, millisecond |
monthly = sales.resample("ME", on="order_date")["revenue"].sum() # calendar monthsprint(monthly.tail(3).round(0))q = sales.groupby([sales["order_date"].dt.to_period("Q"), "channel"])["revenue"].sum()print(q.unstack().tail(2).round(0))daily = sales.groupby("order_date")["revenue"].sum()trend = pd.DataFrame({"rev": daily, "ma7": daily.rolling(7).mean(), "d7": daily.rolling("7D").sum(), "chg": daily.pct_change()})print(trend.tail(2).round(2))d = sales["order_date"].head(1)print(d.dt.day_name().item(), d.dt.day_of_week.item(), d.dt.isocalendar().week.item())order_date2024-10-31 166148.02024-11-30 268467.02024-12-31 302912.0Freq: ME, Name: revenue, dtype: float64channel online storeorder_date2024Q3 200792.0 241643.02024Q4 384905.0 352621.0 rev ma7 d7 chgorder_date2024-12-30 14734.24 8382.76 58679.29 0.582024-12-31 7961.18 8609.74 60268.21 -0.46Sunday 6 52| Window | Call | Note |
|---|---|---|
last n rows |
s.rolling(n).mean() |
NaN until n values; min_periods= lowers that |
| last 7 days | s.rolling("7D").sum() |
needs a sorted DatetimeIndex; robust to missing days |
| centered | s.rolling(7, center=True) |
uses future values: not for forecasts |
| from the start | s.expanding().max(), s.cummax() |
running totals and records |
| weighted to recent rows | s.ewm(span=7).mean() |
|
| previous value | s.shift(1), s.diff(), s.pct_change() |
shift(-1) reads the future |
| per group | df.groupby(k)[c].transform(lambda s: s.rolling(3).mean()) |
sort by time first |
Text with .str
Section titled “Text with .str”| Method | Does |
|---|---|
lower(), upper(), title(), strip() |
case and whitespace |
contains(pat, case=False, regex=True), startswith, endswith |
boolean masks |
fullmatch(r"C\d{5}") |
the whole value matches a pattern |
replace(pat, repl, regex=False) |
substitute text (pass regex=True for patterns) |
split(sep, n=1, expand=True) |
split into columns |
extract(r"(?P<num>\d+)-(?P<unit>\w+)") |
one column per group, named by the group |
len(), str[:3], zfill(5), pad(8) |
length, slicing, padding |
normalize("NFC") |
unify Unicode forms of accents |
cat(sep=", ") |
join all values into one string |
names = pd.Series([" Running Socks 3-Pack", "55-inch 4K TV ", None])clean = names.str.strip().str.lower()print(clean.to_list(), clean.str.contains("pack").to_list())print(names.str.extract(r"(?P<num>\d+)-(?P<unit>inch|Pack)").to_dict("list"))print(names.str.split(" ", n=1, expand=True).shape, clean.str.len().to_list())['running socks 3-pack', '55-inch 4k tv', nan] [True, False, False]{'num': ['3', '55', nan], 'unit': ['Pack', 'inch', nan]}(3, 2) [20.0, 13.0, nan]Method chaining
Section titled “Method chaining”A chain reads top to bottom, creates no temporary names, and never mutates its input.
def add_weekday(frame: pd.DataFrame) -> pd.DataFrame: return frame.assign(weekday=frame["order_date"].dt.day_name())
top_days = ( sales .query("category == 'Books' and order_date.dt.year == 2024") # filter .pipe(add_weekday) # your own step .groupby("weekday") .agg(revenue=("revenue", "sum"), orders=("order_id", "nunique")) .assign(share=lambda d: d["revenue"] / d["revenue"].sum()) # sees the chain .sort_values(["share", "orders"], ascending=False) .head(2))print(top_days) revenue orders shareweekdaySaturday 11544.66 258 0.201Sunday 9509.37 231 0.166| Step | In a chain |
|---|---|
assign(new=lambda d: ...) |
add or replace columns; the lambda sees the current frame |
query("..."), loc[lambda d: ...] |
filter rows |
pipe(func, *args) |
call func(df, *args) |
rename(columns=...), astype({...}) |
rename, change dtypes |
sort_values, head, nlargest, reset_index |
order and trim |
Copy-on-write
Section titled “Copy-on-write”pandas 3 always uses copy-on-write (CoW). Every selection or method result behaves as a copy. pandas copies the data only when one side is written to, so selections stay cheap.
| Code | pandas 3 behavior | Do this |
|---|---|---|
sub = df[df["a"] > 1]; sub["b"] = 0 |
changes sub only, no warning |
fine; df is safe |
df["b"][mask] = 0 |
changes nothing; ChainedAssignmentError warning |
df.loc[mask, "b"] = 0 |
df.loc[mask]["b"] = 0 |
changes nothing; warning | df.loc[mask, "b"] = 0 |
s = df["b"]; s.iloc[0] = 9 |
changes s only |
write through df.loc / df.iloc |
arr = df["b"].to_numpy() |
a read-only view | .to_numpy().copy() to edit |
df.copy() |
still useful for a clear, independent working table | |
SettingWithCopyWarning |
gone | CoW replaced it |
sub = df[df["units"] > 10]sub["units"] = 0 # writes only to subprint(df["units"].to_list(), sub["units"].to_list())col = df["units"]col.iloc[0] = -1 # col is a copy nowprint(df.at["a", "units"], col.iloc[0])fixed = df.copy()fixed.loc[fixed["units"] > 10, "units"] = 10 # the right way to writeprint(fixed["units"].to_list())[12, 7, 15, 4, 9, 11] [0, 0, 0]12 -1[10, 7, 10, 4, 9, 10]df["units"][df["units"] > 10] = 0 # ChainedAssignmentError warning; df is unchangedpandas 3: removed and deprecated APIs
Section titled “pandas 3: removed and deprecated APIs”| Old code | pandas 3 | Use instead |
|---|---|---|
text columns are object |
text is str |
select_dtypes(include="str"), dtype == "str" |
select_dtypes(include="object") for text |
Pandas4Warning |
include="str" |
df[col][mask] = v |
does nothing, warns | df.loc[mask, col] = v |
df.loc[0, "int_col"] = 1.5 |
TypeError (no silent upcast) |
df["int_col"] = df["int_col"].astype("float64") first |
s[0] on a text index |
KeyError (no positional fallback) |
s.iloc[0] |
inplace=True on sort_values, dropna, drop, rename, set_index, reset_index, drop_duplicates, query |
Pandas4Warning |
df = df.sort_values(...) |
df.applymap(f) |
removed | df.map(f) |
fillna(method="ffill") |
TypeError |
ffill(), bfill() |
df.pad(), df.first("2D"), df.swapaxes, s.ravel() |
removed | ffill(), df.loc[:start + offset], df.T, s.to_numpy().ravel() |
df.append(other) |
removed | pd.concat([df, other]) |
freq="M", "Q", "Y", "H", "T", "S" |
ValueError |
"ME", "QE", "YE", "h", "min", "s" |
.dt.weekday, .dt.dayofweek |
Pandas4Warning |
.dt.day_of_week |
.dt.week, .dt.weekofyear |
removed | .dt.isocalendar().week |
groupby(..., axis=1) |
TypeError |
df.T.groupby(...) |
groupby().apply(f, include_groups=True) |
ValueError |
select the columns f needs |
read_csv(delim_whitespace=True) |
TypeError |
sep=r"\s+" |
to_datetime(infer_datetime_format=True) |
TypeError |
format=... or format="ISO8601" |
to_json() with datetimes |
Pandas4Warning |
date_format="iso" |
stack() dropped NaN cells |
keeps them | .dropna() after stack() |
pd.options.mode.copy_on_write |
deprecated; CoW is always on | remove the option |
.values |
still works; a pandas array for text | .to_numpy() |
datetime64[ns] everywhere |
datetime64[us] from parsing |
do not hard-code ns |
ints = pd.DataFrame({"n": [1, 2]})ints.loc[0, "n"] = 1.5 # pandas 3 refuses to upcast int64 silentlyTypeError: Invalid value '1.5' for dtype 'int64'Gotchas
Section titled “Gotchas”| Trap | Symptom | Fix |
|---|---|---|
and, or, not on a Series |
ValueError: The truth value of a Series is ambiguous |
&, |, ~ |
df["a"] > 1 & df["b"] < 2 |
ValueError (ambiguous truth value) or TypeError: & binds first |
parentheses around each test |
| chained assignment | the table does not change | df.loc[mask, col] = value |
loc vs iloc slices |
one row more or fewer than expected | loc includes the end label; iloc excludes it |
iloc[0] after a filter or sort |
not the row labeled 0 | use loc for labels |
print(df.info()) |
an extra None line |
call df.info() alone |
to_csv without index=False |
Unnamed: 0 column on the next read |
index=False |
| CSV round trip | dates and categories come back as str |
Parquet, or parse_dates and dtype on read |
| an int column with one blank | loads as float64 |
dtype={"col": "Int64"} |
pivot_table without aggfunc |
averages, not totals | always pass aggfunc |
pivot with duplicate pairs |
ValueError: Index contains duplicate entries |
pivot_table with aggfunc |
agg result assigned as a column |
all NaN (labels do not match) |
transform |
| merge on a duplicated key | silently more rows | validate= and compare len() |
| clashing columns after a merge | _x and _y names |
select columns first or set suffixes |
sum of an all-NaN group |
0.0, which looks like a real total |
sum(min_count=1) gives NaN |
groupby on a key with gaps |
the NaN rows vanish |
dropna=False or fill the key |
errors="coerce" |
bad values become NaN silently | count isna() before and after |
format="mixed", dayfirst=True |
ISO dates read as year-day-month | parse each known format explicitly |
s.map(dict) |
NaN for missing keys | s.map(d).fillna(s) or check the keys |
>= on an unordered category |
TypeError |
CategoricalDtype(..., ordered=True) |
rolling(7) vs rolling("7D") |
different numbers when days are missing | pick rows or days on purpose |
a sort with ties, then head() |
unstable top rows | add a tie-breaker column |
str.replace("$", "") with regex=True |
removes nothing ($ is an anchor) |
regex=False or [$] |
astype("int8") on big values |
wraps around silently | pd.to_numeric(downcast="integer") |
apply(axis=1) on big tables |
very slow | vectorized column math, np.where, map |
df.equals(other) |
False on a dtype difference you cannot see |
pd.testing.assert_frame_equal for a clear message |
Learn more
Section titled “Learn more”- Module 24: pandas fundamentals and its cheat sheet
- Module 25: pandas advanced and its cheat sheet
- Module 26: data cleaning and its cheat sheet
- Module 27: exploratory data analysis and its cheat sheet
- Master cheat sheet: NumPy, Polars and SQL and DuckDB