Skip to content

pandas

The examples share one table of 20 cancer genes with simulated fold changes and p-values. The page ran with pandas 3.1. pandas 3 changed two defaults that older tutorials rely on: text columns now have the str dtype, and copy on write is always on. Both show up below where they change a result. For a slower introduction, start with Pandas Essentials.

Task Code
Label and position slices df.loc[0:2, cols], df.iloc[:2, :3]
Rows by key df.set_index("symbol").loc[keys]
Filter df[(df["a"] > 1) & (df["b"] < 0.05)]
Match a list df[df["col"].isin(values)]
String filter df.query("p < @max_p")
Sort df.sort_values(["a", "b"], key=abs)
Top n df.nlargest(3, "col")
New columns df.assign(new=lambda d: d["x"] * 2)
Labels from conditions np.select(conditions, labels, default="ns")
Set values df.loc[mask, "col"] = value
Map with a dict df["col"].map(mapping)
Group summary df.groupby("g").agg(n=("x", "size"))
Group key to column and back df.reset_index(), df.set_index("g")
Per row group value df.groupby("g")["x"].transform("mean")
Top rows per group df.sort_values("p").groupby("g").head(2)
Counts, cross table value_counts(), pd.crosstab(a, b)
Proportions s.value_counts(normalize=True)
Bin numbers pd.cut(s, bins=edges, labels=names)
Text to columns df["col"].str.extract(pattern)
One row per list item df.assign(x=s.str.split(";")).explode("x")
Join df.merge(other, on="key", how="left")
Anti join df.merge(other, on="key", how="left_anti")
Stack pd.concat([df1, df2], ignore_index=True)
Flag repeats df["key"].duplicated(keep=False)
One row per key df.sort_values("x", ascending=False).drop_duplicates("key")
Wide to long df.melt(id_vars="id", var_name="sample")
Long to wide df.pivot(index="id", columns="sample", values="x")
Long to wide with repeats df.pivot_table(..., aggfunc="mean")
Missing values isna().sum(), dropna(subset=["x"]), fillna(0)
TSV pd.read_csv(f, sep="\t"), df.to_csv(f, sep="\t")
Parquet pd.read_parquet(f), df.to_parquet(f)

The chromosome and the oncogene or suppressor role are real for each gene. The fold changes, p-values, and mean counts are random.

import numpy as np
import pandas as pd
pd.set_option("display.width", 80)
rng = np.random.default_rng(42)
symbols = ["TP53", "BRCA1", "EGFR", "MYC", "KRAS", "PIK3CA", "PTEN",
"RB1", "APC", "VHL", "CDH1", "NF1", "BRAF", "IDH1", "CTNNB1",
"SMAD4", "ALK", "RET", "KIT", "MET"]
chromosomes = ["chr17", "chr17", "chr7", "chr8", "chr12", "chr3", "chr10",
"chr13", "chr5", "chr3", "chr16", "chr17", "chr7", "chr2",
"chr3", "chr18", "chr2", "chr10", "chr4", "chr7"]
suppressors = {"TP53", "BRCA1", "PTEN", "RB1", "APC", "VHL", "CDH1",
"NF1", "SMAD4"}
genes = pd.DataFrame({
"symbol": symbols,
"chromosome": chromosomes,
"role": ["suppressor" if s in suppressors else "oncogene"
for s in symbols],
"log2fc": rng.normal(0, 2, 20).round(2),
"pvalue": rng.uniform(0.0001, 0.2, 20).round(4),
"basemean": rng.uniform(50, 5000, 20).round(1),
})
print(genes.head())
symbol chromosome role log2fc pvalue basemean
0 TP53 chr17 suppressor 0.61 0.1516 2213.9
1 BRCA1 chr17 suppressor -2.08 0.0710 4171.8
2 EGFR chr7 oncogene 1.50 0.1941 3516.3
3 MYC chr8 oncogene 1.88 0.1786 1596.2
4 KRAS chr12 oncogene -3.90 0.1557 4169.7

pandas 2 listed text columns as object. pandas 3 lists them as str.

print(genes.shape)
print(genes.dtypes)
(20, 6)
symbol str
chromosome str
role str
log2fc float64
pvalue float64
basemean float64
dtype: object

A loc slice includes its end label. An iloc slice stops before its end position.

print(genes.loc[0:2, ["symbol", "log2fc", "pvalue"]])
print(genes.iloc[:2, :3])
symbol log2fc pvalue
0 TP53 0.61 0.1516
1 BRCA1 -2.08 0.0710
2 EGFR 1.50 0.1941
symbol chromosome role
0 TP53 chr17 suppressor
1 BRCA1 chr17 suppressor
by_symbol = genes.set_index("symbol")
print(by_symbol.loc[["TP53", "EGFR"], ["log2fc", "pvalue"]])
log2fc pvalue
symbol
TP53 0.61 0.1516
EGFR 1.50 0.1941

Combine conditions with & and |, and wrap each one in parentheses.

sig_up = genes[(genes["log2fc"] > 1) & (genes["pvalue"] < 0.05)]
print(sig_up[["symbol", "log2fc", "pvalue"]])
symbol log2fc pvalue
18 KIT 1.76 0.0455

isin keeps the rows whose value appears in a list, such as a gene panel.

panel = ["TP53", "KRAS", "EGFR", "BRAF"]
print(genes.loc[genes["symbol"].isin(panel), ["symbol", "chromosome"]])
symbol chromosome
0 TP53 chr17
2 EGFR chr7
4 KRAS chr12
12 BRAF chr7

query reads a filter from a string. Prefix a Python variable with @.

max_p = 0.05
hits = genes.query("pvalue < @max_p and role == 'oncogene'")
print(hits[["symbol", "role", "pvalue"]])
symbol role pvalue
5 PIK3CA oncogene 0.0390
16 ALK oncogene 0.0261
18 KIT oncogene 0.0455
by_role = genes.sort_values(["role", "pvalue"], ascending=[True, True])
print(by_role[["symbol", "role", "pvalue"]].head(4))
symbol role pvalue
16 ALK oncogene 0.0261
5 PIK3CA oncogene 0.0390
18 KIT oncogene 0.0455
12 BRAF oncogene 0.0652

key= transforms the column before the sort, here to rank by absolute fold change.

by_size = genes.sort_values("log2fc", key=abs, ascending=False)
print(by_size[["symbol", "log2fc"]].head(4))
symbol log2fc
4 KRAS -3.90
5 PIK3CA -2.60
13 IDH1 2.25
1 BRCA1 -2.08
print(genes.nlargest(3, "basemean")[["symbol", "basemean"]])
print(genes.nsmallest(3, "pvalue")[["symbol", "pvalue"]])
symbol basemean
1 BRCA1 4171.8
4 KRAS 4169.7
5 PIK3CA 4033.6
symbol pvalue
7 RB1 0.0089
16 ALK 0.0261
8 APC 0.0309

assign returns a new frame, and each lambda sees the columns made before it. false_discovery_control from SciPy gives Benjamini-Hochberg adjusted p-values.

from scipy.stats import false_discovery_control
genes = genes.assign(
padj=lambda d: false_discovery_control(d["pvalue"]),
neg_log10p=lambda d: -np.log10(d["pvalue"]),
)
print(genes[["symbol", "pvalue", "padj", "neg_log10p"]].head().round(3))
symbol pvalue padj neg_log10p
0 TP53 0.152 0.183 0.819
1 BRCA1 0.071 0.159 1.149
2 EGFR 0.194 0.194 0.712
3 MYC 0.179 0.194 0.748
4 KRAS 0.156 0.183 0.808

np.select takes the first condition that matches. Series.case_when does the same job inside pandas.

conditions = [
(genes["log2fc"] > 1) & (genes["pvalue"] < 0.05),
(genes["log2fc"] < -1) & (genes["pvalue"] < 0.05),
]
genes["direction"] = np.select(conditions, ["up", "down"], default="ns")
print(genes[["symbol", "log2fc", "pvalue", "direction"]].head(6))
symbol log2fc pvalue direction
0 TP53 0.61 0.1516 ns
1 BRCA1 -2.08 0.0710 ns
2 EGFR 1.50 0.1941 ns
3 MYC 1.88 0.1786 ns
4 KRAS -3.90 0.1557 ns
5 PIK3CA -2.60 0.0390 down

Set values with one .loc[rows, column] call. Under pandas 3 a chained form such as df[mask]["log2fc"] = np.nan never changes df. It only raises a ChainedAssignmentError warning.

filtered = genes.copy()
filtered.loc[filtered["basemean"] < 500, "log2fc"] = np.nan
print(filtered["log2fc"].isna().sum())
1

A symbol missing from the dictionary maps to NaN.

ensembl = {"TP53": "ENSG00000141510", "BRCA1": "ENSG00000012048",
"EGFR": "ENSG00000146648", "MYC": "ENSG00000136997"}
print(genes["symbol"].map(ensembl).head(6))
0 ENSG00000141510
1 ENSG00000012048
2 ENSG00000146648
3 ENSG00000136997
4 NaN
5 NaN
Name: symbol, dtype: str

String columns add element by element. apply(..., axis=1) gives the same labels but makes one Python call per row.

genes["label"] = genes["symbol"] + " (" + genes["direction"] + ")"
print(genes.loc[genes["direction"] != "ns", "label"].tolist())
['PIK3CA (down)', 'SMAD4 (down)', 'KIT (up)']

Named aggregation sets the output column names. A one line lambda covers a statistic that has no built in name.

summary = genes.groupby("role").agg(
n_genes=("symbol", "size"),
mean_log2fc=("log2fc", "mean"),
n_p05=("pvalue", lambda p: (p < 0.05).sum()),
).round(2)
print(summary)
n_genes mean_log2fc n_p05
role
oncogene 11 0.06 3
suppressor 9 -0.22 3

transform returns one value per row, so the result fits back into the frame.

role_mean = genes.groupby("role")["log2fc"].transform("mean")
genes["log2fc_vs_role"] = genes["log2fc"] - role_mean
print(genes[["symbol", "role", "log2fc", "log2fc_vs_role"]].head(4).round(2))
symbol role log2fc log2fc_vs_role
0 TP53 suppressor 0.61 0.83
1 BRCA1 suppressor -2.08 -1.86
2 EGFR oncogene 1.50 1.44
3 MYC oncogene 1.88 1.82

Sort first, then head on the groups keeps the top rows of each role.

top = genes.sort_values("pvalue").groupby("role").head(2)
print(top[["symbol", "role", "pvalue"]])
symbol role pvalue
7 RB1 suppressor 0.0089
16 ALK oncogene 0.0261
8 APC suppressor 0.0309
5 PIK3CA oncogene 0.0390

groupby puts the group key in the index. reset_index moves it back to a column, and set_index makes a column the index again for label lookup.

summary_flat = summary.reset_index()
print(summary_flat)
print(summary_flat.set_index("role").loc["oncogene", "n_genes"])
role n_genes mean_log2fc n_p05
0 oncogene 11 0.06 3
1 suppressor 9 -0.22 3
11
print(genes["chromosome"].value_counts().head(4))
print(pd.crosstab(genes["role"], genes["direction"]))
chromosome
chr17 3
chr7 3
chr3 3
chr10 2
Name: count, dtype: int64
direction down ns up
role
oncogene 1 9 1
suppressor 1 8 0
print(genes[["log2fc", "pvalue", "basemean"]].describe().round(2))
log2fc pvalue basemean
count 20.00 20.00 20.00
mean -0.07 0.10 2486.50
std 1.74 0.06 1372.39
min -3.90 0.01 86.40
25% -1.71 0.04 1367.78
50% 0.20 0.09 2593.45
75% 1.52 0.15 3634.10
max 2.25 0.19 4171.80

normalize=True returns the share of each value in place of the count.

print(genes["role"].value_counts(normalize=True))
role
oncogene 0.55
suppressor 0.45
Name: proportion, dtype: float64

pd.cut assigns each value to a bin. The bins include their right edge, so 1000 falls in low.

genes["expr_bin"] = pd.cut(
genes["basemean"],
bins=[0, 1000, 3000, np.inf],
labels=["low", "mid", "high"],
)
print(genes["expr_bin"].value_counts(sort=False))
expr_bin
low 4
mid 7
high 9
Name: count, dtype: int64

The .str accessor works on the whole column. removeprefix converts UCSC chromosome names to Ensembl names.

print(genes["chromosome"].str.removeprefix("chr").head(3).tolist())
print(genes.loc[genes["symbol"].str.startswith("B"), "symbol"].tolist())
['17', '17', '7']
['BRCA1', 'BRAF']

str.extract splits a locus string into named columns. The captured parts are text, so convert them before any arithmetic.

loci = pd.Series(["chr17:7661779-7687538", "chr7:55019017-55211628"])
parts = loci.str.extract(r"(?P<chrom>\w+):(?P<start>\d+)-(?P<end>\d+)")
parts = parts.astype({"start": int, "end": int})
print(parts.assign(width=parts["end"] - parts["start"]))
chrom start end width
0 chr17 7661779 7687538 25759
1 chr7 55019017 55211628 192611

str.split turns a delimited column into lists, and explode gives each list item its own row. ignore_index=True numbers the new rows from zero.

go = pd.DataFrame({
"symbol": ["TP53", "BRCA1", "EGFR"],
"go_terms": ["GO:0006915;GO:0006974", "GO:0006281;GO:0006974",
"GO:0007169"],
})
go_long = go.assign(go_term=go["go_terms"].str.split(";")).explode(
"go_term", ignore_index=True
)
print(go_long[["symbol", "go_term"]])
symbol go_term
0 TP53 GO:0006915
1 TP53 GO:0006974
2 BRCA1 GO:0006281
3 BRCA1 GO:0006974
4 EGFR GO:0007169

ATM is in the pathway table and not in the gene table. indicator=True adds a _merge column that says where each row came from.

pathways = pd.DataFrame({
"symbol": ["TP53", "BRCA1", "EGFR", "KRAS", "PTEN", "ATM"],
"pathway": ["p53 signaling", "DNA repair", "EGFR signaling",
"MAPK signaling", "PI3K signaling", "DNA repair"],
})
outer = genes[["symbol", "log2fc"]].merge(
pathways, on="symbol", how="outer", indicator=True
)
print(outer["_merge"].value_counts())
_merge
left_only 15
both 5
right_only 1
Name: count, dtype: int64
inner = genes[["symbol", "log2fc"]].merge(pathways, on="symbol", how="inner")
print(inner)
symbol log2fc pathway
0 TP53 0.61 p53 signaling
1 BRCA1 -2.08 DNA repair
2 EGFR 1.50 EGFR signaling
3 KRAS -3.90 MAPK signaling
4 PTEN 0.26 PI3K signaling

how="left_anti" keeps the genes with no pathway. pandas 2 has no anti join, so older code negates isin instead: genes[~genes["symbol"].isin(pathways["symbol"])].

no_pathway = genes[["symbol", "log2fc"]].merge(
pathways[["symbol"]], on="symbol", how="left_anti"
)
print(no_pathway.head(5))
symbol log2fc
3 MYC 1.88
5 PIK3CA -2.60
7 RB1 -0.63
8 APC -0.03
9 VHL -1.71

DataFrame.append is gone since pandas 2. Use pd.concat.

run_one = genes.iloc[:2][["symbol", "log2fc"]].assign(batch="run1")
run_two = genes.iloc[2:4][["symbol", "log2fc"]].assign(batch="run2")
print(pd.concat([run_one, run_two], ignore_index=True))
symbol log2fc batch
0 TP53 0.61 run1
1 BRCA1 -2.08 run1
2 EGFR 1.50 run2
3 MYC 1.88 run2

A microarray often has several probes for one gene. duplicated(keep=False) flags every copy, and the default flags only the second and later ones.

probes = pd.DataFrame({
"symbol": ["TP53", "MYC", "MYC", "EGFR", "EGFR"],
"probe": ["p1", "p2", "p3", "p4", "p5"],
"basemean": [2213.9, 1596.2, 310.5, 3516.3, 4022.0],
})
print(probes[probes["symbol"].duplicated(keep=False)])
print(probes["symbol"].duplicated().sum())
symbol probe basemean
1 MYC p2 1596.2
2 MYC p3 310.5
3 EGFR p4 3516.3
4 EGFR p5 4022.0
2

Sort so the row you want comes first, then drop_duplicates keeps the first row per symbol. Here that is the probe with the highest basemean.

best = probes.sort_values("basemean", ascending=False).drop_duplicates(
subset="symbol", keep="first"
)
print(best.sort_index())
symbol probe basemean
0 TP53 p1 2213.9
1 MYC p2 1596.2
4 EGFR p5 4022.0

melt turns one column per sample into one row per gene and sample.

expr_wide = pd.DataFrame({
"symbol": ["TP53", "BRCA1", "EGFR"],
"ctrl_1": [10.2, 8.5, 12.1],
"ctrl_2": [10.6, 8.1, 11.8],
"trt_1": [15.3, 6.2, 18.4],
"trt_2": [14.9, 6.6, 17.9],
})
expr_long = expr_wide.melt(
id_vars="symbol", var_name="sample", value_name="expression"
)
expr_long["condition"] = expr_long["sample"].str.split("_").str[0]
print(expr_long.head(4))
symbol sample expression condition
0 TP53 ctrl_1 10.2 ctrl
1 BRCA1 ctrl_1 8.5 ctrl
2 EGFR ctrl_1 12.1 ctrl
3 TP53 ctrl_2 10.6 ctrl

pivot goes back to one column per sample. It raises an error when a gene and sample pair appears twice.

print(expr_long.pivot(index="symbol", columns="sample", values="expression"))
sample ctrl_1 ctrl_2 trt_1 trt_2
symbol
BRCA1 8.5 8.1 6.2 6.6
EGFR 12.1 11.8 18.4 17.9
TP53 10.2 10.6 15.3 14.9

pivot_table aggregates the repeats, here the two replicates per condition.

per_condition = expr_long.pivot_table(
index="symbol", columns="condition", values="expression", aggfunc="mean"
)
print(per_condition)
condition ctrl trt
symbol
BRCA1 8.30 6.40
EGFR 11.95 18.15
TP53 10.40 15.10

filtered has a NaN fold change wherever basemean was under 500.

print(filtered[["log2fc", "pvalue"]].isna().sum())
print(len(filtered), len(filtered.dropna(subset=["log2fc"])))
log2fc 1
pvalue 0
dtype: int64
20 19

Assign the filled column back. Under pandas 3, filtered["log2fc"].fillna(0, inplace=True) leaves filtered unchanged.

filtered["log2fc"] = filtered["log2fc"].fillna(0)
print(filtered["log2fc"].isna().sum())
0

A .gz suffix compresses the file. usecols reads only the columns you name.

from pathlib import Path
out_dir = Path("outputs")
out_dir.mkdir(exist_ok=True)
table = genes[["symbol", "chromosome", "log2fc", "pvalue"]]
table.to_csv(out_dir / "genes.tsv.gz", sep="\t", index=False)
back = pd.read_csv(
out_dir / "genes.tsv.gz", sep="\t", usecols=["symbol", "log2fc"]
)
print(back.head(3))
symbol log2fc
0 TP53 0.61
1 BRCA1 -2.08
2 EGFR 1.50

Parquet stores the dtypes in the file, so the read does not have to guess them.

table.to_parquet(out_dir / "genes.parquet", index=False)
print(pd.read_parquet(out_dir / "genes.parquet").dtypes)
symbol str
chromosome str
log2fc float64
pvalue float64
dtype: object

Each call in the left column fails or does nothing under pandas 3.1.

Old call Use now
df.append(other) pd.concat([df, other])
df.applymap(f) df.map(f)
df.iteritems() df.items()
df.fillna(method="ffill") df.ffill()
pd.read_csv(f, delim_whitespace=True) pd.read_csv(f, sep=r"\s+")
df[mask]["col"] = x df.loc[mask, "col"] = x
df["col"].fillna(0, inplace=True) df["col"] = df["col"].fillna(0)
  • Pandas Essentials builds these operations up from a first DataFrame.
  • Data Wrangling works through filters, joins, groups, and reshapes on an RNA-seq counts table, with dplyr and Polars side by side.
  • The Polars cheatsheet runs the same gene table, and the NumPy cheatsheet covers the arrays underneath.

McKinney, 2010 describes the pandas data structures for statistical computing in Python.

  • pandas: 10 minutes to pandas

    The guide explains label and position selection, missing values, grouping, joins, and reshaping. Its small tables help check intermediate results before applying the same operations to the gene table.