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.
Quick reference
Section titled “Quick reference”| 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 npimport 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 basemean0 TP53 chr17 suppressor 0.61 0.1516 2213.91 BRCA1 chr17 suppressor -2.08 0.0710 4171.82 EGFR chr7 oncogene 1.50 0.1941 3516.33 MYC chr8 oncogene 1.88 0.1786 1596.24 KRAS chr12 oncogene -3.90 0.1557 4169.7Inspect
Section titled “Inspect”pandas 2 listed text columns as object. pandas 3 lists them as str.
print(genes.shape)print(genes.dtypes)(20, 6)symbol strchromosome strrole strlog2fc float64pvalue float64basemean float64dtype: objectSelect by label and by position
Section titled “Select by label and by position”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 pvalue0 TP53 0.61 0.15161 BRCA1 -2.08 0.07102 EGFR 1.50 0.1941 symbol chromosome role0 TP53 chr17 suppressor1 BRCA1 chr17 suppressorLook up rows by gene symbol
Section titled “Look up rows by gene symbol”by_symbol = genes.set_index("symbol")print(by_symbol.loc[["TP53", "EGFR"], ["log2fc", "pvalue"]]) log2fc pvaluesymbolTP53 0.61 0.1516EGFR 1.50 0.1941Filter rows
Section titled “Filter rows”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 pvalue18 KIT 1.76 0.0455isin 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 chromosome0 TP53 chr172 EGFR chr74 KRAS chr1212 BRAF chr7query reads a filter from a string. Prefix a Python variable with @.
max_p = 0.05hits = genes.query("pvalue < @max_p and role == 'oncogene'")print(hits[["symbol", "role", "pvalue"]]) symbol role pvalue5 PIK3CA oncogene 0.039016 ALK oncogene 0.026118 KIT oncogene 0.0455by_role = genes.sort_values(["role", "pvalue"], ascending=[True, True])print(by_role[["symbol", "role", "pvalue"]].head(4)) symbol role pvalue16 ALK oncogene 0.02615 PIK3CA oncogene 0.039018 KIT oncogene 0.045512 BRAF oncogene 0.0652key= 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 log2fc4 KRAS -3.905 PIK3CA -2.6013 IDH1 2.251 BRCA1 -2.08print(genes.nlargest(3, "basemean")[["symbol", "basemean"]])print(genes.nsmallest(3, "pvalue")[["symbol", "pvalue"]]) symbol basemean1 BRCA1 4171.84 KRAS 4169.75 PIK3CA 4033.6 symbol pvalue7 RB1 0.008916 ALK 0.02618 APC 0.0309Add columns with assign
Section titled “Add columns with assign”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_log10p0 TP53 0.152 0.183 0.8191 BRCA1 0.071 0.159 1.1492 EGFR 0.194 0.194 0.7123 MYC 0.179 0.194 0.7484 KRAS 0.156 0.183 0.808Label rows by condition
Section titled “Label rows by condition”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 direction0 TP53 0.61 0.1516 ns1 BRCA1 -2.08 0.0710 ns2 EGFR 1.50 0.1941 ns3 MYC 1.88 0.1786 ns4 KRAS -3.90 0.1557 ns5 PIK3CA -2.60 0.0390 downChange values in place
Section titled “Change values in place”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.nanprint(filtered["log2fc"].isna().sum())1Map values with a dictionary
Section titled “Map values with a dictionary”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 ENSG000001415101 ENSG000000120482 ENSG000001466483 ENSG000001369974 NaN5 NaNName: symbol, dtype: strCombine columns without apply
Section titled “Combine columns without apply”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)']Group and summarize
Section titled “Group and summarize”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_p05roleoncogene 11 0.06 3suppressor 9 -0.22 3transform 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_meanprint(genes[["symbol", "role", "log2fc", "log2fc_vs_role"]].head(4).round(2)) symbol role log2fc log2fc_vs_role0 TP53 suppressor 0.61 0.831 BRCA1 suppressor -2.08 -1.862 EGFR oncogene 1.50 1.443 MYC oncogene 1.88 1.82Sort 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 pvalue7 RB1 suppressor 0.008916 ALK oncogene 0.02618 APC suppressor 0.03095 PIK3CA oncogene 0.0390Index after a groupby
Section titled “Index after a groupby”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_p050 oncogene 11 0.06 31 suppressor 9 -0.22 311Count values
Section titled “Count values”print(genes["chromosome"].value_counts().head(4))print(pd.crosstab(genes["role"], genes["direction"]))chromosomechr17 3chr7 3chr3 3chr10 2Name: count, dtype: int64direction down ns uproleoncogene 1 9 1suppressor 1 8 0print(genes[["log2fc", "pvalue", "basemean"]].describe().round(2)) log2fc pvalue basemeancount 20.00 20.00 20.00mean -0.07 0.10 2486.50std 1.74 0.06 1372.39min -3.90 0.01 86.4025% -1.71 0.04 1367.7850% 0.20 0.09 2593.4575% 1.52 0.15 3634.10max 2.25 0.19 4171.80Proportions with value_counts
Section titled “Proportions with value_counts”normalize=True returns the share of each value in place of the count.
print(genes["role"].value_counts(normalize=True))roleoncogene 0.55suppressor 0.45Name: proportion, dtype: float64Bin a numeric column
Section titled “Bin a numeric column”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_binlow 4mid 7high 9Name: count, dtype: int64String methods
Section titled “String methods”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 width0 chr17 7661779 7687538 257591 chr7 55019017 55211628 192611One row per GO term
Section titled “One row per GO term”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_term0 TP53 GO:00069151 TP53 GO:00069742 BRCA1 GO:00062813 BRCA1 GO:00069744 EGFR GO:0007169Join tables
Section titled “Join tables”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())_mergeleft_only 15both 5right_only 1Name: count, dtype: int64inner = genes[["symbol", "log2fc"]].merge(pathways, on="symbol", how="inner")print(inner) symbol log2fc pathway0 TP53 0.61 p53 signaling1 BRCA1 -2.08 DNA repair2 EGFR 1.50 EGFR signaling3 KRAS -3.90 MAPK signaling4 PTEN 0.26 PI3K signalinghow="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 log2fc3 MYC 1.885 PIK3CA -2.607 RB1 -0.638 APC -0.039 VHL -1.71Stack tables
Section titled “Stack tables”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 batch0 TP53 0.61 run11 BRCA1 -2.08 run12 EGFR 1.50 run23 MYC 1.88 run2Find duplicated gene IDs
Section titled “Find duplicated gene IDs”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 basemean1 MYC p2 1596.22 MYC p3 310.53 EGFR p4 3516.34 EGFR p5 4022.02Keep one row per gene
Section titled “Keep one row per gene”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 basemean0 TP53 p1 2213.91 MYC p2 1596.24 EGFR p5 4022.0Reshape
Section titled “Reshape”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 condition0 TP53 ctrl_1 10.2 ctrl1 BRCA1 ctrl_1 8.5 ctrl2 EGFR ctrl_1 12.1 ctrl3 TP53 ctrl_2 10.6 ctrlpivot 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_2symbolBRCA1 8.5 8.1 6.2 6.6EGFR 12.1 11.8 18.4 17.9TP53 10.2 10.6 15.3 14.9pivot_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 trtsymbolBRCA1 8.30 6.40EGFR 11.95 18.15TP53 10.40 15.10Missing values
Section titled “Missing values”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 1pvalue 0dtype: int6420 19Assign 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())0Read and write files
Section titled “Read and write files”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 log2fc0 TP53 0.611 BRCA1 -2.082 EGFR 1.50Parquet 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 strchromosome strlog2fc float64pvalue float64dtype: objectCalls older tutorials use
Section titled “Calls older tutorials use”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) |
See also
Section titled “See also”- 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.
Scientific references
Section titled “Scientific references”McKinney, 2010 describes the pandas data structures for statistical computing in Python.
Further reading
Section titled “Further reading”-
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.