Skip to content

The AnnData Object

Scanpy keeps the count matrix, the cell and gene tables, and every later result in one AnnData object. This page loads the PBMC 3k matrix into that object and saves it to disk.

# AnnData is the core data structure
# adata.X - count matrix (cells x genes)
# adata.obs - cell metadata (DataFrame)
# adata.var - gene metadata (DataFrame)
# adata.obsm - embeddings (PCA, UMAP)
# adata.layers - alternative matrices (raw, normalized)
# adata.uns - unstructured data

The source matrix is 10x Genomics’ PBMC 3k dataset, processed with Cell Ranger 1.1.0 and published in 2016. The provider licenses it under CC BY 4.0. This lesson converts the matrix to AnnData and derives the displayed summaries and analysis results.

import scanpy as sc
sc.settings.verbosity = 3
# The PBMC 3k matrix ships in the section container at /opt/data/pbmc3k.
adata = sc.read_10x_mtx("/opt/data/pbmc3k", var_names="gene_symbols",
make_unique=True)
# Store the raw counts before anything modifies adata.X.
adata.layers["counts"] = adata.X.copy()
print(adata)
AnnData object with n_obs × n_vars = 2700 × 32738
var: 'gene_ids'
layers: None (.X), 'counts'

The object holds 2,700 cells and 32,738 genes. Cells are the rows and genes the columns, the reverse of the matrix files that Cell Ranger writes. The counts layer keeps a copy of the raw matrix, so later steps can change adata.X and still reach the original counts.

print(adata.var.head())
print(adata.X[:4, :4].toarray())
gene_ids
MIR1302-10 ENSG00000243485
FAM138A ENSG00000237613
OR4F5 ENSG00000186092
RP11-34P13.7 ENSG00000238009
RP11-34P13.8 ENSG00000239945
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]

The gene table uses the gene symbol as its index and keeps the Ensembl ID in gene_ids. None of the first four genes has a count in the first four cells, which is the normal case in this matrix.

Most entries of a single-cell count matrix are zero. A zero has one of two causes:

  • The cell expresses the gene at a low level, and none of its few molecules was captured and sequenced. This sampling zero is what the term dropout describes.
  • The cell does not express the gene. This is a true biological zero.
zero_fraction = 1.0 - adata.X.nnz / (adata.n_obs * adata.n_vars)
print(f"fraction of zero entries: {zero_fraction:.4f}")
fraction of zero entries: 0.9741

In PBMC 3k, 97.41 percent of the entries are zero. adata.X therefore stores only the nonzero values as a sparse matrix, and the code calls .toarray() before it prints a slice.

adata.write_h5ad("outputs/anndata-object_pbmc3k.h5ad")
adata_copy = sc.read_h5ad("outputs/anndata-object_pbmc3k.h5ad")
print(adata_copy)
AnnData object with n_obs × n_vars = 2700 × 32738
var: 'gene_ids'
layers: 'counts', None (.X)

The h5ad file keeps the whole object. The reloaded copy has the same 2,700 by 32,738 shape and the same counts layer, so a later session can start here instead of from the 10x files.

Wolf, Angerer, and Theis, 2018 describe Scanpy, the Python toolkit for large-scale single-cell expression analysis.

The AnnData introduction defines observations, variables, layers, and multidimensional annotations. These axes determine how a subset stays aligned.

The 10x Genomics PBMC 3k record identifies the matrix loaded into the example object. The h5ad file stores a derived representation of this dataset.