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.
Run the examples
Section titled “Run the examples”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.
Creating a DataFrame
Section titled “Creating a DataFrame”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 biotype0 TP53 2.5 0.0010 protein_coding1 BRCA1 -1.8 0.0030 protein_coding2 EGFR 3.2 0.0001 protein_coding3 KRAS 0.3 0.4500 protein_coding4 MYC -2.1 0.0020 protein_coding5 PTEN 1.5 0.0100 protein_coding6 RB1 -0.2 0.6700 protein_coding7 APC 0.8 0.1200 protein_codingThe numbers on the left are the index. By default, pandas assigns integer indices starting at 0.
Basic inspection
Section titled “Basic inspection”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 strlog2fc float64pvalue float64biotype strdtype: objectUse .head() to preview the first few rows. Pass an integer to control how many rows you see.
print(degs.head(3)) gene log2fc pvalue biotype0 TP53 2.5 0.0010 protein_coding1 BRCA1 -1.8 0.0030 protein_coding2 EGFR 3.2 0.0001 protein_codingUse .describe() to get summary statistics for numeric columns.
print(degs.describe()) log2fc pvaluecount 8.000000 8.000000mean 0.525000 0.157012std 1.888121 0.258758min -2.100000 0.00010025% -0.600000 0.00175050% 0.550000 0.00650075% 1.750000 0.202500max 3.200000 0.670000This is useful for spotting outliers or unexpected ranges in expression data.
Selecting columns
Section titled “Selecting columns”Use bracket notation with a column name to select a single column. This returns a Series.
print(degs["gene"])0 TP531 BRCA12 EGFR3 KRAS4 MYC5 PTEN6 RB17 APCName: gene, dtype: strTo select multiple columns, pass a list of column names inside the brackets.
print(degs[["gene", "log2fc"]]) gene log2fc0 TP53 2.51 BRCA1 -1.82 EGFR 3.23 KRAS 0.34 MYC -2.15 PTEN 1.56 RB1 -0.27 APC 0.8Note the double brackets. The outer brackets are the selection operator. The inner brackets define the list.
Filtering rows
Section titled “Filtering rows”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 biotype0 TP53 2.5 0.0010 protein_coding1 BRCA1 -1.8 0.0030 protein_coding2 EGFR 3.2 0.0001 protein_coding4 MYC -2.1 0.0020 protein_coding5 PTEN 1.5 0.0100 protein_codingNotice 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 biotype0 TP53 2.5 0.0010 protein_coding2 EGFR 3.2 0.0001 protein_coding5 PTEN 1.5 0.0100 protein_codingThis 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.
loc and iloc
Section titled “loc and iloc”Pandas provides two indexers for precise row and column selection.
locselects by label. You provide row labels and column names.ilocselects by integer position. You provide row and column indices as numbers.
print(degs.loc[0, "gene"])TP53print(degs.iloc[0:3, 0:2]) gene log2fc0 TP53 2.51 BRCA1 -1.82 EGFR 3.2With iloc, the slice 0:3 means rows 0, 1, and 2. The upper bound is excluded, just like standard Python slicing.
Adding columns
Section titled “Adding columns”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 direction0 TP53 2.5 0.0010 3.000000 up1 BRCA1 -1.8 0.0030 2.522879 down2 EGFR 3.2 0.0001 4.000000 up3 KRAS 0.3 0.4500 0.346787 up4 MYC -2.1 0.0020 2.698970 down5 PTEN 1.5 0.0100 2.000000 up6 RB1 -0.2 0.6700 0.173925 down7 APC 0.8 0.1200 0.920819 upnp.where() works like an if/else applied to every row. If log2fc > 0, the value is "up". Otherwise, it is "down".
Sorting
Section titled “Sorting”Sorting by p-value puts the smallest raw p-values at the top.
print(degs.sort_values("pvalue")[["gene", "pvalue"]]) gene pvalue2 EGFR 0.00010 TP53 0.00104 MYC 0.00201 BRCA1 0.00305 PTEN 0.01007 APC 0.12003 KRAS 0.45006 RB1 0.6700Use 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 log2fc2 EGFR 3.20 TP53 2.55 PTEN 1.5groupby
Section titled “groupby”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_samplesconditioncontrol 175.00 2 1treated 261.25 4 2Named 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.
Reshaping data
Section titled “Reshaping data”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 Sample30 TP53 100 120 901 BRCA1 250 300 2802 EGFR 50 75 60expression_long = expression_wide.melt( id_vars="gene", var_name="sample", value_name="count",)print(expression_long) gene sample count0 TP53 Sample1 1001 BRCA1 Sample1 2502 EGFR Sample1 503 TP53 Sample2 1204 BRCA1 Sample2 3005 EGFR Sample2 756 TP53 Sample3 907 BRCA1 Sample3 2808 EGFR Sample3 60Long 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 Sample3geneBRCA1 250 300 280EGFR 50 75 60TP53 100 120 90Note 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.
Reading and writing files
Section titled “Reading and writing files”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 pvalue0 TP53 2.5 0.00101 BRCA1 -1.8 0.00302 EGFR 3.2 0.00013 KRAS 0.3 0.45004 MYC -2.1 0.00205 PTEN 1.5 0.01006 RB1 -0.2 0.67007 APC 0.8 0.1200Pandas 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.
Align sample labels before arithmetic
Section titled “Align sample labels before arithmetic”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 / baselineprint("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.3S2 1.3dtype: float64Incorrect 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: MergeErrorSamples absent from metadata: ['S3']Measurements before and after: 6 6The 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 batch0 S1 TP53 100 B11 S1 BRCA1 250 B12 S2 TP53 450 B23 S2 BRCA1 120 B24 S3 TP53 380 B25 S3 BRCA1 95 B2pandas 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] = 999print("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"] = 30print("Parent after direct loc assignment:", measurements["count"].tolist())Changed selected column: [999, 20]Parent after the selection changes: [10, 20]Chained assignment rejected: ChainedAssignmentErrorParent 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.
Practice before combining tables
Section titled “Practice before combining tables”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.Quick reference
Section titled “Quick reference”| 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) |
Next steps
Section titled “Next steps”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.
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 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.