Skip to content

Pandas Essentials

Pandas represents labeled tables with a DataFrame. Columns can hold different types, while row labels identify entries for selection and alignment. This lesson uses invented gene results and sample counts to demonstrate those operations.

Use a uv project with pandas and NumPy installed. Save the Python blocks in page order as pandas_essentials.py, then run uv run python pandas_essentials.py from that project. The final example creates a TSV file under outputs/. The examples use pandas 3.1.1. Copy-on-Write behavior below requires pandas 3.0 or later; the earlier pandas 2 defaults differ.

You can build a DataFrame from a Python dictionary. Each key becomes a column name. Each value is a list of entries for that column.

The invented results contain one row per gene, with a log2 fold change, raw p-value, and biotype label. Some rows do not pass the filters used later.

from pathlib import Path
import pandas as pd
degs = pd.DataFrame({
"gene": ["TP53", "BRCA1", "EGFR", "KRAS", "MYC", "PTEN", "RB1", "APC"],
"log2fc": [2.5, -1.8, 3.2, 0.3, -2.1, 1.5, -0.2, 0.8],
"pvalue": [0.001, 0.003, 0.0001, 0.45, 0.002, 0.01, 0.67, 0.12],
"biotype": ["protein_coding"] * 8,
})
print(degs)
gene log2fc pvalue biotype
0 TP53 2.5 0.0010 protein_coding
1 BRCA1 -1.8 0.0030 protein_coding
2 EGFR 3.2 0.0001 protein_coding
3 KRAS 0.3 0.4500 protein_coding
4 MYC -2.1 0.0020 protein_coding
5 PTEN 1.5 0.0100 protein_coding
6 RB1 -0.2 0.6700 protein_coding
7 APC 0.8 0.1200 protein_coding

The numbers on the left are the index. By default, pandas assigns integer indices starting at 0.

Before analyzing any dataset, inspect its size and types. The .shape attribute returns rows and columns as a tuple.

print(degs.shape)
(8, 4)

This tells us we have 8 genes and 4 columns.

Use .dtypes to check the data type of each column.

print(degs.dtypes)
gene str
log2fc float64
pvalue float64
biotype str
dtype: object

Use .head() to preview the first few rows. Pass an integer to control how many rows you see.

print(degs.head(3))
gene log2fc pvalue biotype
0 TP53 2.5 0.0010 protein_coding
1 BRCA1 -1.8 0.0030 protein_coding
2 EGFR 3.2 0.0001 protein_coding

Use .describe() to get summary statistics for numeric columns.

print(degs.describe())
log2fc pvalue
count 8.000000 8.000000
mean 0.525000 0.157012
std 1.888121 0.258758
min -2.100000 0.000100
25% -0.600000 0.001750
50% 0.550000 0.006500
75% 1.750000 0.202500
max 3.200000 0.670000

This is useful for spotting outliers or unexpected ranges in expression data.

Use bracket notation with a column name to select a single column. This returns a Series.

print(degs["gene"])
0 TP53
1 BRCA1
2 EGFR
3 KRAS
4 MYC
5 PTEN
6 RB1
7 APC
Name: gene, dtype: str

To select multiple columns, pass a list of column names inside the brackets.

print(degs[["gene", "log2fc"]])
gene log2fc
0 TP53 2.5
1 BRCA1 -1.8
2 EGFR 3.2
3 KRAS 0.3
4 MYC -2.1
5 PTEN 1.5
6 RB1 -0.2
7 APC 0.8

Note the double brackets. The outer brackets are the selection operator. The inner brackets define the list.

Filtering retains rows that satisfy a condition. This example applies a raw p-value threshold to teach selection syntax. For a discovery claim across many genes, define the test family and use the appropriate multiple-testing correction.

To filter, place a boolean condition inside brackets.

sig = degs[degs["pvalue"] < 0.05]
print(sig)
gene log2fc pvalue biotype
0 TP53 2.5 0.0010 protein_coding
1 BRCA1 -1.8 0.0030 protein_coding
2 EGFR 3.2 0.0001 protein_coding
4 MYC -2.1 0.0020 protein_coding
5 PTEN 1.5 0.0100 protein_coding

Notice that rows 3, 6, and 7 are gone. Their p-values were above 0.05.

You can combine conditions with & for AND and | for OR. Wrap each condition in parentheses.

sig_up = degs[(degs["pvalue"] < 0.05) & (degs["log2fc"] > 1)]
print(sig_up)
gene log2fc pvalue biotype
0 TP53 2.5 0.0010 protein_coding
2 EGFR 3.2 0.0001 protein_coding
5 PTEN 1.5 0.0100 protein_coding

This selects rows with a raw p-value below the threshold and a log2 fold change above one. The filter does not calculate an adjusted p-value.

Pandas provides two indexers for precise row and column selection.

  • loc selects by label. You provide row labels and column names.
  • iloc selects by integer position. You provide row and column indices as numbers.
print(degs.loc[0, "gene"])
TP53
print(degs.iloc[0:3, 0:2])
gene log2fc
0 TP53 2.5
1 BRCA1 -1.8
2 EGFR 3.2

With iloc, the slice 0:3 means rows 0, 1, and 2. The upper bound is excluded, just like standard Python slicing.

You can create new columns from existing ones. This is useful for derived metrics like negative log10 p-values, which are standard in volcano plots.

import numpy as np
degs["neg_log10p"] = -np.log10(degs["pvalue"])
degs["direction"] = np.where(degs["log2fc"] > 0, "up", "down")
print(degs[["gene", "log2fc", "pvalue", "neg_log10p", "direction"]])
gene log2fc pvalue neg_log10p direction
0 TP53 2.5 0.0010 3.000000 up
1 BRCA1 -1.8 0.0030 2.522879 down
2 EGFR 3.2 0.0001 4.000000 up
3 KRAS 0.3 0.4500 0.346787 up
4 MYC -2.1 0.0020 2.698970 down
5 PTEN 1.5 0.0100 2.000000 up
6 RB1 -0.2 0.6700 0.173925 down
7 APC 0.8 0.1200 0.920819 up

np.where() works like an if/else applied to every row. If log2fc > 0, the value is "up". Otherwise, it is "down".

Sorting by p-value puts the smallest raw p-values at the top.

print(degs.sort_values("pvalue")[["gene", "pvalue"]])
gene pvalue
2 EGFR 0.0001
0 TP53 0.0010
4 MYC 0.0020
1 BRCA1 0.0030
5 PTEN 0.0100
7 APC 0.1200
3 KRAS 0.4500
6 RB1 0.6700

Use ascending=False to sort in descending order. Here it identifies the largest positive log2 fold changes.

print(degs.sort_values("log2fc", ascending=False)[["gene", "log2fc"]].head(3))
gene log2fc
2 EGFR 3.2
0 TP53 2.5
5 PTEN 1.5

Grouping computes summaries per category. Each row below represents one gene measurement in one sample, so a sample identifier occurs on more than one row.

sample_counts = pd.DataFrame({
"sample": ["S1", "S1", "S2", "S2", "S3", "S3"],
"gene": ["TP53", "BRCA1", "TP53", "BRCA1", "TP53", "BRCA1"],
"condition": [
"control", "control", "treated", "treated", "treated", "treated"
],
"count": [100, 250, 450, 120, 380, 95],
})
grouped = sample_counts.groupby("condition").agg(
mean_count=("count", "mean"),
n_measurements=("count", "count"),
n_samples=("sample", "nunique"),
)
print(grouped)
mean_count n_measurements n_samples
condition
control 175.00 2 1
treated 261.25 4 2

Named aggregations give each result an explicit column name. count counts nonmissing measurements, while nunique counts distinct sample identifiers. The mean pools both genes within each condition; include gene in the grouping keys when the question concerns a separate mean for each gene.

Bioinformatics tools often expect data in a specific shape. Some need one row per gene per sample. Others need a gene-by-sample matrix. Pandas provides melt and pivot to convert between these formats.

melt converts wide format to long format. Wide format has one column per sample. Long format has one row per observation.

expression_wide = pd.DataFrame({
"gene": ["TP53", "BRCA1", "EGFR"],
"Sample1": [100, 250, 50],
"Sample2": [120, 300, 75],
"Sample3": [90, 280, 60],
})
print(expression_wide)
gene Sample1 Sample2 Sample3
0 TP53 100 120 90
1 BRCA1 250 300 280
2 EGFR 50 75 60
expression_long = expression_wide.melt(
id_vars="gene",
var_name="sample",
value_name="count",
)
print(expression_long)
gene sample count
0 TP53 Sample1 100
1 BRCA1 Sample1 250
2 EGFR Sample1 50
3 TP53 Sample2 120
4 BRCA1 Sample2 300
5 EGFR Sample2 75
6 TP53 Sample3 90
7 BRCA1 Sample3 280
8 EGFR Sample3 60

Long format lets a plotting or summary function select its grouping variables from columns. A matrix-based method can require the wide representation instead.

pivot does the reverse. It converts long format back to wide format.

back_to_wide = expression_long.pivot(
index="gene",
columns="sample",
values="count",
)
print(back_to_wide)
sample Sample1 Sample2 Sample3
gene
BRCA1 250 300 280
EGFR 50 75 60
TP53 100 120 90

Note that the rows are now sorted alphabetically by gene name. The gene column has become the index.

Each gene and sample pair must identify one measurement for pivot. A repeated pair raises an error; use an explicit aggregation only when multiple measurements have a defined meaning.

Most bioinformatics data lives in CSV or TSV files. Pandas can read and write both formats.

Use .to_csv() to write a DataFrame to a file. Set sep="\t" for tab-separated output. Set index=False to avoid writing the row numbers.

output_dir = Path("outputs")
output_dir.mkdir(exist_ok=True)
output_path = output_dir / "degs.tsv"
degs[["gene", "log2fc", "pvalue"]].to_csv(
output_path, sep="\t", index=False
)
read_back = pd.read_csv(output_path, sep="\t")
print(read_back)
gene log2fc pvalue
0 TP53 2.5 0.0010
1 BRCA1 -1.8 0.0030
2 EGFR 3.2 0.0001
3 KRAS 0.3 0.4500
4 MYC -2.1 0.0020
5 PTEN 1.5 0.0100
6 RB1 -0.2 0.6700
7 APC 0.8 0.1200

Pandas can also read Excel files with pd.read_excel() and compressed files directly. For example, pd.read_csv("data.tsv.gz", sep="\t") will decompress and read in one step.

Two series can contain the same samples in different row orders. pandas aligns their labels before arithmetic. Converting both series to NumPy first removes that matching rule and can combine values from different samples.

baseline = pd.Series([100.0, 200.0], index=["S1", "S2"], name="baseline")
followup = pd.Series([260.0, 130.0], index=["S2", "S1"], name="followup")
sample_ratios = followup / baseline
print("Ratios matched by sample:")
print(sample_ratios)
print("Incorrect positional ratios:",
followup.to_numpy() / baseline.to_numpy())
ordered_followup = followup.reindex(baseline.index)
assert ordered_followup.index.equals(baseline.index)
print("Ratios after explicit reindex:",
ordered_followup.to_numpy() / baseline.to_numpy())
Ratios matched by sample:
S1 1.3
S2 1.3
dtype: float64
Incorrect positional ratios: [2.6 0.65]
Ratios after explicit reindex: [1.3 1.3]

reindex makes the requested order explicit, but an absent label introduces a missing value. Check uniqueness and missing identifiers before exporting aligned arrays to a library that no longer carries sample labels.

Verify the relationship in a metadata merge

Section titled “Verify the relationship in a metadata merge”

Each sample occurs once per measured gene in sample_counts. A metadata table with one batch per sample should therefore join through a many-to-one relationship. A repeated sample in that metadata would multiply measurements.

duplicate_metadata = pd.DataFrame({
"sample": ["S1", "S2", "S2"],
"batch": ["B1", "B2", "B3"],
})
try:
sample_counts.merge(
duplicate_metadata, on="sample", how="left", validate="many_to_one"
)
except pd.errors.MergeError as error:
print("Repeated metadata key rejected:", type(error).__name__)
incomplete_metadata = pd.DataFrame({
"sample": ["S1", "S2"],
"batch": ["B1", "B2"],
})
checked_merge = sample_counts.merge(
incomplete_metadata,
on="sample",
how="left",
validate="many_to_one",
indicator="sample_match",
)
unmatched_samples = checked_merge.loc[
checked_merge["sample_match"] == "left_only", "sample"
].unique()
print("Samples absent from metadata:", unmatched_samples.tolist())
print("Measurements before and after:", len(sample_counts), len(checked_merge))
Repeated metadata key rejected: MergeError
Samples absent from metadata: ['S3']
Measurements before and after: 6 6

The validation checks key multiplicity. It does not require every left key to appear on the right, which is why the indicator needs a separate check. For these invented records, the complete metadata explicitly assigns S3 to batch B2. A real analysis must obtain that assignment from its sample records.

complete_metadata = pd.DataFrame({
"sample": ["S1", "S2", "S3"],
"batch": ["B1", "B2", "B2"],
})
assert sample_counts["sample"].notna().all()
assert complete_metadata["sample"].notna().all()
annotated_counts = sample_counts.merge(
complete_metadata,
on="sample",
how="left",
validate="many_to_one",
indicator="sample_match",
)
assert annotated_counts["sample_match"].eq("both").all()
assert len(annotated_counts) == len(sample_counts)
print(annotated_counts[["sample", "gene", "count", "batch"]])
sample gene count batch
0 S1 TP53 100 B1
1 S1 BRCA1 250 B1
2 S2 TP53 450 B2
3 S2 BRCA1 120 B2
4 S3 TP53 380 B2
5 S3 BRCA1 95 B2

pandas can match null join keys with other null keys. Reject missing identifiers before this merge when every measurement must belong to a named sample. The join lesson explains other relationships through Polars, and the duplicate lesson shows how to inspect repeated keys.

Modify the intended object with Copy-on-Write

Section titled “Modify the intended object with Copy-on-Write”

In pandas 3, a derived DataFrame or Series behaves independently when you modify it. Changing a selected column does not update its parent DataFrame. Use one .loc assignment on the object that should change.

import warnings
measurements = pd.DataFrame({"sample": ["S1", "S2"], "count": [10, 20]})
selected_column = measurements["count"]
selected_column.iloc[0] = 999
print("Changed selected column:", selected_column.tolist())
print("Parent after the selection changes:", measurements["count"].tolist())
with warnings.catch_warnings():
warnings.simplefilter("error", pd.errors.ChainedAssignmentError)
try:
measurements["count"][measurements["sample"] == "S1"] = 30
except pd.errors.ChainedAssignmentError as error:
print("Chained assignment rejected:", type(error).__name__)
measurements.loc[measurements["sample"] == "S1", "count"] = 30
print("Parent after direct loc assignment:", measurements["count"].tolist())
Changed selected column: [999, 20]
Parent after the selection changes: [10, 20]
Chained assignment rejected: ChainedAssignmentError
Parent after direct loc assignment: [30, 20]

The warning filter turns this specific warning into an exception so the failed assignment is visible. The direct .loc assignment identifies both the target rows and column on measurements. NumPy views follow different rules, as the array lesson demonstrates.

A result table contains samples in a different order from its metadata. One metadata identifier repeats, and another sample has no metadata row. Explain which check detects each problem. Then explain why converting to NumPy before the checks loses information needed to match samples.

Show the explanation and executable checks.

A validated merge rejects duplicate right keys under the many-to-one contract. The merge indicator finds missing matches. Label-aware arithmetic or an explicit reindex handles different orders, while arrays carry positions only.

assert sample_ratios.to_dict() == {"S1": 1.3, "S2": 1.3}
assert unmatched_samples.tolist() == ["S3"]
assert annotated_counts["batch"].tolist() == [
"B1", "B1", "B2", "B2", "B2", "B2"
]
assert measurements["count"].tolist() == [30, 20]
assert selected_column.tolist() == [999, 20]
print("Alignment, unmatched samples, batch labels, and assignment checks pass.")
Alignment, unmatched samples, batch labels, and assignment checks pass.
Operation Code
Create DataFrame pd.DataFrame({"col": [values]})
Check shape df.shape
Check types df.dtypes
Preview rows df.head(n)
Summary stats df.describe()
Select one column df["col"]
Select multiple columns df[["col1", "col2"]]
Filter rows df[df["col"] > value]
Combine filters df[(cond1) & (cond2)]
Select by label df.loc[row, col]
Select by position df.iloc[row, col]
Add column df["new"] = expression
Sort df.sort_values("col")
Group and aggregate df.groupby("col").agg(["mean"])
Wide to long df.melt(id_vars="col")
Long to wide df.pivot(index="gene", columns="sample", values="count")
Read TSV pd.read_csv("file.tsv", sep="\t")
Write TSV df.to_csv("file.tsv", sep="\t", index=False)

Read Polars Essentials to compare these table operations with expression-based queries. The Data Wrangling section develops joins, duplicate keys, and missing values through additional examples.

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

The introduction covers selection, grouping, and reshaping with DataFrame objects. See 10 minutes to pandas.

The pivot reference defines the named arguments and the unique-pair requirement. Use it when a long table cannot be reshaped without aggregating repeated measurements.

The alignment guide explains label matching during arithmetic. The merge reference defines key validation, match indicators, and the treatment of null keys.

The Copy-on-Write migration guide explains the pandas 3 assignment rules. Use its examples to distinguish a change to a derived object from a direct change to its parent.