Skip to main content
v2026.11,986 entries · CC-BY 4.0

AnnData: Annotated Data Matrices for Single-Cell Analysis in Python

What AnnData stores, how to install it, subset, save and reload objects, and how Scanpy and R’s zellkonverter use it.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

AnnData is a Python package for handling annotated data matrices, in memory and on disk. Its documentation describes it as sitting between pandas and xarray, with support for sparse matrices and lazy operations, and it was originally built for Scanpy, the Python toolkit for single-cell analysis. An AnnData object keeps one observations-by-variables matrix together with the labels that describe its rows and columns, so that subsetting, filtering and saving never let the numbers drift out of step with their annotations. In single-cell work the rows are cells and the columns are genes; the package itself does not require that interpretation.

This page covers what each part of an AnnData object holds, how to install and create one, how to subset, save and reload it, how a Scanpy workflow fills its slots, and how R users exchange data with it. Commands are taken from the current official documentation (read 2026-11-13). The slot reference table below the article lists the shape rules from the on-disk format specification.

What AnnData is used for in research

Single-cell and other high-dimensional experiments produce a matrix plus a lot of side information: per-cell quality metrics, cluster labels, per-gene flags, low-dimensional embeddings and free-form parameters. Keeping these in separate variables invites mistakes when a filter removes cells from the matrix but not from the label vector. AnnData stores them as one object and subsets them together.

The package was introduced to the literature in a Journal of Open Source Software paper by Virshup, Rybakov, Theis, Angerer and Wolf (2024), doi:10.21105/joss.04371. Cite that paper when AnnData is part of your analysis pipeline. Downstream tools that read and write AnnData include Scanpy, and the format is the interchange point for other pages on this site such as CELLxGENE, SpatialData and decoupler.

Anatomy of an AnnData object

The file-format specification names the top-level elements of the object: X, layers, obs, obsm, obsp, uns, var, varm and varp. In short:

  • X is the main matrix, with n_obs rows and n_var columns. It is optional and may be dense or sparse.
  • obs and var are pandas DataFrames that annotate the rows and columns. They must be present, though they may contain only an index.
  • layers hold extra matrices with the same shape as X, for example raw counts alongside normalised values.
  • obsm and varm hold multi-dimensional annotations (arrays, sparse matrices or data frames) whose first dimension matches n_obs or n_var.
  • obsp and varp hold pairwise relations, such as graphs, whose first two dimensions match the observations or variables.
  • uns is an unstructured mapping for anything else, such as parameters.

The data table at the end of this page sets out each slot with its content and shape rule.

How to install or access it

AnnData is distributed on PyPI and conda-forge, and the official installation commands are:

pip install anndataconda install anndata -c conda-forge

On the date this page was checked (2026-11-13), the PyPI project page listed version 0.13.4, released 2026-09-18, with a BSD-3-Clause licence and a requirement of Python 3.12 or newer. The stable documentation header showed a slightly different version string (0.13.3.post0), so confirm the installed version with ad.__version__ and report it in your methods section. The PyPI page lists optional extras named dask, lazy, gpu, cu11, cu12 and cu13; install them with the usual pip extras syntax only if you need those features.

Documentation lives at anndata.readthedocs.io, and the package is free to install under its open-source licence.

Step-by-step: build, subset, save and reload an AnnData object

The steps below follow the official Getting Started tutorial.

1. Create the object

Pass a matrix to the constructor. The tutorial uses a sparse matrix of random Poisson counts with 100 cells and 2,000 genes:

import anndata as adimport numpy as npimport pandas as pdfrom scipy.sparse import csr_matrixcounts = csr_matrix(np.random.poisson(1, size=(100, 2000)), dtype=np.float32)adata = ad.AnnData(counts)

2. Name the rows and columns

adata.obs_names = [f"Cell_{i:d}" for i in range(adata.n_obs)]adata.var_names = [f"Gene_{i:d}" for i in range(adata.n_vars)]

3. Add annotations

Because obs and var are pandas DataFrames, annotations are added as columns. A categorical column is created with pd.Categorical:

adata.obs["cell_type"] = pd.Categorical(ct)

where ct is a list of labels, one per cell. The raw matrix stays available as adata.X.

4. Subset

Subset by names or by a boolean condition on an annotation column:

adata[["Cell_1", "Cell_10"], ["Gene_5", "Gene_1900"]]bdata = adata[adata.obs.cell_type == "B"]

Integer indices behave like pandas iloc and string indices like loc.

5. Save

adata.write_zarr("my_results.zarr")adata.write_h5ad("my_results.h5ad")

The tutorial recommends Zarr over h5ad for performance and cloud use. For the trade-offs between the two container formats, see the comparison of HDF5, Zarr and Parquet; AnnData’s h5ad files are HDF5 and its Zarr stores are Zarr, as the file-format specification states.

6. Reload, including without loading everything into memory

adata = ad.read_h5ad("my_results.h5ad")adata_backed = ad.read_h5ad("my_results.h5ad", backed="r")lazy = ad.experimental.read_lazy("my_results.zarr")adata_backed.file.close()

backed="r" keeps the matrix on disk and reads on demand; close the file handle with .file.close() when finished. ad.experimental.read_lazy is the lazy reader the tutorial shows for Zarr stores. Because it sits under experimental, check the API page for your installed version before depending on it in a long-lived pipeline.

Other readers and concatenation

The API reference lists readers for formats you may receive from other tools: io.read_h5ad, io.read_zarr, io.read_csv, io.read_excel, io.read_hdf (for .h5), io.read_mtx, io.read_text (for .txt, .tab and .data) and io.read_umi_tools. To join several objects along an axis, use ad.concat.

Worked example: how a Scanpy workflow fills the slots

The Scanpy clustering tutorial shows how a typical single-cell workflow writes results into an AnnData object rather than returning separate tables. The following sequence is taken from that tutorial.

  1. Read each sample. sample_adata = sc.read_10x_h5(path), then sample_adata.var_names_make_unique() so duplicate gene names do not collide.
  2. Combine samples. adata = ad.concat(adatas, label="sample") adds a sample column to adata.obs recording which object each cell came from.
  3. Flag gene groups. adata.var["mt"] = adata.var_names.str.startswith("MT-") marks mitochondrial genes in var.
  4. Compute quality metrics. sc.pp.calculate_qc_metrics(adata, qc_vars=["mt", "ribo", "hb"], inplace=True, log1p=True) writes per-cell metrics into adata.obs, including n_genes_by_counts, total_counts and pct_counts_mt and their log1p versions.
  5. Doublet detection. The Scrublet step adds doublet_score and predicted_doublet to adata.obs.
  6. Preserve counts. adata.layers["counts"] = adata.X.copy() is run before normalisation, so the raw counts remain in a layer while X then holds normalised, log-transformed values.
  7. Cluster. sc.tl.leiden(adata, flavor="igraph", n_iterations=2) stores cluster labels as a categorical column named leiden in adata.obs; the key_added option changes the column name.

The practical lesson is that obs accumulates the per-cell results of every step, var the per-gene flags, and layers the alternative versions of the matrix. A reviewer who receives the saved file can see which metrics and thresholds were available for filtering without rerunning the pipeline. For a downstream example of a trajectory method that starts from a Seurat or SingleCellExperiment object instead, see Monocle 3.

Output and how to read it

Printing an AnnData object summarises its contents: the dimensions (n_obs × n_vars) and the names of the columns and keys present in each slot. Use that summary to confirm that a step wrote where you expected, then inspect the slot directly: adata.obs.head() is an ordinary pandas DataFrame, and adata.X is a dense array or a SciPy sparse matrix.

Views versus copies

Subsetting returns a view, which does not allocate new memory for the data. Call .copy() to make an independent object. If you modify the obs of a view, AnnData makes a copy automatically and emits a warning. Treat that warning as a signal to call .copy() explicitly at the moment you intend to branch an analysis.

What is on disk

The on-disk specification says an AnnData object is stored as HDF5 (a .h5ad file, written through h5py) or as Zarr. Each element carries encoding-type and encoding-version attributes, and the root group has an anndata encoding at version 0.1.0. Sparse matrices are stored as a group holding data, indices and indptr arrays, in CSR or CSC form. Categorical columns are stored as integer codes (with -1 meaning missing), a categories array and an ordered flag. Awkward arrays are described as experimental.

Troubleshooting

  • A warning appears when you edit a subset. You modified a view. Create the subset with .copy() before changing its annotations.
  • Raw counts are gone after normalisation. Normalisation overwrites X. Save counts first with adata.layers["counts"] = adata.X.copy(), as the Scanpy tutorial does.
  • Duplicate gene names cause problems after loading. Call var_names_make_unique() after reading, as in the Scanpy tutorial.
  • The file will not close or is locked after a backed read. Run adata_backed.file.close() when you are finished with the object.
  • Installation fails on an older Python. The PyPI page for the checked release requires Python 3.12 or newer.
  • A layer or obsm entry is rejected. Check the shape rules: layers must match the shape of X; obsm entries must match n_obs in their first dimension.

Using AnnData data from R

R users have a documented bridge. The Bioconductor package zellkonverter converts between a SingleCellExperiment and an AnnData object, with readH5AD() and writeH5AD() for h5ad files and SCE2AnnData() and AnnData2SCE() for in-memory conversion. It relies on reticulate and the Python anndata package, and its vignette recommends using basilisk to manage the Python environment; AnnDataDependencies() reports the Python dependencies it expects. The vignette’s example shows an assay named X and a colData column cell_type after conversion; check the vignette for the exact mapping of your own slots before relying on it.

Free alternatives and neighbours

AnnData and the tools around it are open source. The table compares the routes the official documentation describes for working with the same kind of data.

Route Language What the documentation says
anndata (this page) Python Annotated data matrices in memory and on disk; sparse and lazy operations; BSD-3-Clause on PyPI.
Scanpy Python Analysis toolkit whose tutorials operate directly on AnnData objects.
zellkonverter R (Bioconductor) Converts between SingleCellExperiment and AnnData and reads and writes h5ad files.

Frequently asked questions

What is AnnData?

A Python package whose central object stores a data matrix together with annotations for its rows and columns, in memory or on disk. It was originally built for Scanpy.

How do I install AnnData?

Run pip install anndata or conda install anndata -c conda-forge.

What is a .h5ad file?

An AnnData object saved in HDF5 format with write_h5ad. AnnData can also write Zarr stores with write_zarr, which the tutorial recommends for performance and cloud use.

Does AnnData work with R?

Not natively, but the Bioconductor package zellkonverter reads and writes h5ad files and converts between SingleCellExperiment and AnnData.

Why does editing a subset raise a warning?

Subsets are views. Changing a view’s obs triggers an automatic copy and a warning; use .copy() first.

Sources

  • AnnData documentation, anndata.readthedocs.io/en/stable/ (read 2026-11-13), including the Getting Started tutorial, API reference and file-format specification.
  • AnnData on PyPI, pypi.org/project/anndata/ (read 2026-11-13).
  • Virshup I, Rybakov S, Theis FJ, Angerer P, Wolf FA. anndata: Annotated data. Journal of Open Source Software (2024), doi:10.21105/joss.04371.
  • Scanpy clustering tutorial, scanpy.readthedocs.io/en/stable/tutorials/basics/clustering.html (read 2026-11-13).
  • zellkonverter vignette, bioconductor.org/packages/release/bioc/vignettes/zellkonverter/inst/doc/zellkonverter.html (read 2026-11-13).

Data: AnnData object slots: content and shape rules

Compiled from the AnnData on-disk format specification: for each top-level element of an AnnData object, what it stores and the shape constraint it must satisfy relative to n_obs and n_var.

Period covered: 2026.

AnnData object slots: content and shape rules
SlotContentShape constraintRequired
XMain data matrix, dense or sparse(n_obs, n_var)Optional
layersAdditional matrices, e.g. raw countsSame shape as XOptional
obsRow (observation) annotations as a data frameOne row per observation; may hold only an indexRequired
varColumn (variable) annotations as a data frameOne row per variable; may hold only an indexRequired
obsmMulti-dimensional observation annotations (sparse, dense or data frames)First dimension matches n_obsOptional
varmMulti-dimensional variable annotationsFirst dimension matches n_varOptional
obspPairwise observation relationsFirst two dimensions match n_obsOptional
varpPairwise variable relationsFirst two dimensions match n_varOptional
unsUnstructured mappingNo shape constraintOptional

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about AnnData: Annotated Data Matrices for Single-Cell Analysis in Python

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →