{"data":{"slug":"github-aipoch-medical-research-skills-scientific-skills-data-analysis-anndata-01b4a501419c","title":"Anndata for Single-Cell Data Management","summary":"Use Anndata to manage annotated matrices in single-cell analysis, including reading\/writing .h5ad files and working with the scverse ecosystem. The deliverable is an AnnData object, which stores data matrices and metadata in a unified format.","url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-anndata-01b4a501419c","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-anndata-01b4a501419c","markdown_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-anndata-01b4a501419c.md","download_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-anndata-01b4a501419c\/download","category":{"slug":"data-research","name":"Data & Research"},"editor_note":"Install `anndata`, `numpy`, `pandas`, and `scipy` before use. For sparse matrices, `scipy` is recommended. Optional tools like `scanpy` or `muon` may be needed depending on the task.","instructions":"---\nname: anndata\ndescription: Data structure for annotated matrices in single-cell analysis; use when reading\/writing .h5ad (or zarr) and exchanging data with the scverse ecosystem.\nlicense: MIT\nauthor: AIPOCH\n---\n> **Source**: [https:\/\/github.com\/aipoch\/medical-research-skills](https:\/\/github.com\/aipoch\/medical-research-skills)\n\n## When to Use\n\nUse AnnData when you need to:\n\n- Load, inspect, or export annotated single-cell datasets stored as `.h5ad` (or `zarr`) for downstream tools.\n- Keep a matrix (cells \u00d7 features) tightly coupled with observation\/feature metadata (e.g., cell types, batches, gene annotations).\n- Work efficiently with large, sparse count matrices (e.g., scRNA-seq) and avoid loading everything into memory (backed mode).\n- Combine multiple experiments\/batches\/modalities into a unified object while tracking provenance.\n- Subset\/filter\/transform data while preserving alignment between the matrix and metadata.\n\n## Key Features\n\n- **Unified container**: `X` (data matrix) plus aligned annotations: `obs`, `var`, `uns`, and multi-dimensional slots (`obsm`, `varm`, `obsp`, `varp`), plus `layers` and optional `raw`.\n- **Interoperable I\/O**: Native `.h5ad` and `zarr`, plus common genomics formats (e.g., 10x, loom, mtx, csv).\n- **Scalable workflows**: Sparse matrices and **backed mode** (`backed=\"r\"`) for large datasets.\n- **Safe subsetting**: Slicing preserves alignment across matrix and annotations; supports views vs copies.\n- **Concatenation utilities**: `ad.concat(...)` with join\/merge strategies and batch labeling; experimental lazy collections.\n\n> Reference notes: the original material mentions additional guides under `references\/` (e.g., `references\/data_structure.md`, `references\/io_operations.md`, `references\/concatenation.md`, `references\/manipulation.md`, `references\/best_practices.md`) for deeper explanations of each topic.\n\n## Dependencies\n\n- `anndata` (latest compatible with your environment; install via pip\/uv)\n- `numpy`\n- `pandas`\n- `scipy` (recommended for sparse matrices)\n- Optional ecosystem tools (only if needed):\n  - `scanpy`\n  - `muon`\n  - `torch` (for deep learning) and `anndata` experimental loader utilities\n\n## Example Usage\n\nA complete runnable example that creates an AnnData object, writes\/reads `.h5ad`, subsets, concatenates batches, and demonstrates backed mode.\n\n```python\nimport numpy as np\nimport pandas as pd\nimport anndata as ad\nfrom scipy.sparse import csr_matrix\n\n# ----------------------------\n# 1) Create an AnnData object\n# ----------------------------\nrng = np.random.default_rng(0)\n\nn_cells, n_genes = 100, 500\nX = rng.poisson(1.0, size=(n_cells, n_genes)).astype(np.float32)\n\nobs = pd.DataFrame(\n    {\n        \"cell_type\": ([\"T cell\", \"B cell\"] * (n_cells \/\/ 2)),\n        \"sample\": ([\"A\", \"B\"] * (n_cells \/\/ 2)),\n        \"quality_score\": rng.random(n_cells),\n    },\n    index=[f\"cell_{i}\" for i in range(n_cells)],\n)\n\nvar = pd.DataFrame(\n    {\"gene_name\": [f\"Gene_{j}\" for j in range(n_genes)]},\n    index=[f\"ENSG{j:05d}\" for j in range(n_genes)],\n)\n\nadata = ad.AnnData(X=X, obs=obs, var=var)\n\n# Use sparse storage for typical count-like matrices\nadata.X = csr_matrix(adata.X)\n\n# Convert string columns to categoricals to reduce memory and speed up ops\nadata.strings_to_categoricals()\n\nprint(f\"Created: {adata.n_obs} obs \u00d7 {adata.n_vars} vars\")\n\n# ----------------------------\n# 2) Write and read .h5ad\n# ----------------------------\nadata.write_h5ad(\"example.h5ad\", compression=\"gzip\")\n\nadata2 = ad.read_h5ad(\"example.h5ad\")\nprint(f\"Reloaded: {adata2.n_obs} obs \u00d7 {adata2.n_vars} vars\")\n\n# ----------------------------\n# 3) Subset (keeps alignment)\n# ----------------------------\nt_cells = adata2[adata2.obs[\"cell_type\"] == \"T cell\", :]\nhigh_quality = adata2[adata2.obs[\"quality_score\"] > 0.8, :]\n\nprint(f\"T cells: {t_cells.n_obs}\")\nprint(f\"High quality: {high_quality.n_obs}\")\n\n# ----------------------------\n# 4) Concatenate batches\n# ----------------------------\nadata_a = adata2[adata2.obs[\"sample\"] == \"A\", :].copy()\nadata_b = adata2[adata2.obs[\"sample\"] == \"B\", :].copy()\n\ncombined = ad.concat(\n    [adata_a, adata_b],\n    axis=0,                 # concatenate observations (cells)\n    join=\"inner\",           # keep shared variables\n    label=\"batch\",          # add a column in .obs\n    keys=[\"A\", \"B\"],        # batch labels\n)\n\nprint(combined.obs[\"batch\"].value_counts().to_dict())\n\n# ----------------------------\n# 5) Backed mode for large files\n# ----------------------------\nadata_backed = ad.read_h5ad(\"example.h5ad\", backed=\"r\")\n# Slicing in backed mode is metadata-friendly; load to memory when needed:\nsubset_mem = adata_backed[:10, :50].to_memory()\nprint(f\"Backed subset loaded: {subset_mem.shape}\")\n```\n\n## Implementation Details\n\n### Data model (core slots)\n\n- `X`: primary data matrix (dense `numpy.ndarray` or sparse `scipy.sparse`), shape `(n_obs, n_vars)`.\n- `obs`: per-observation metadata (`pandas.DataFrame`), indexed by `obs_names` (e.g., cell IDs).\n- `var`: per-variable metadata (`pandas.DataFrame`), indexed by `var_names` (e.g., gene IDs).\n- `layers`: named alternative matrices aligned to `X` (e.g., `\"counts\"`, `\"log1p\"`).\n- `obsm` \/ `varm`: multi-dimensional embeddings aligned to obs\/var (e.g., PCA, UMAP coordinates).\n- `obsp` \/ `varp`: pairwise graphs\/matrices (e.g., kNN graph in `obsp[\"connectivities\"]`).\n- `uns`: unstructured metadata (dict-like), often used for parameters and plotting configs.\n- `raw` (optional): snapshot of unfiltered\/untransformed data for reproducibility.\n\n### Views vs copies\n\n- Slicing like `adata_subset = adata[mask, :]` typically returns a **view** (lightweight reference).\n- Use `.copy()` when you need an independent object (e.g., before in-place modifications).\n\n### Backed mode (large datasets)\n\n- `ad.read_h5ad(path, backed=\"r\")` keeps the matrix on disk and loads data lazily.\n- Convert a slice to memory with `.to_memory()` when you need in-memory computation.\n- Backed mode is best for filtering by metadata, chunked processing, and avoiding OOM.\n\n### Concatenation behavior\n\n- `ad.concat([...], axis=0)` stacks observations; `axis=1` stacks variables.\n- `join=\"inner\"` keeps intersection of variables; `join=\"outer\"` unions variables (may introduce missing values).\n- `label` + `keys` records dataset\/batch provenance in `.obs[label]`.\n- Merge strategies control how conflicting `.uns` and annotation columns are handled (choose based on your data governance needs).\n\n### Practical performance parameters\n\n- Prefer sparse matrices (`csr_matrix`) for count-like data.\n- Convert repeated strings to categoricals (`adata.strings_to_categoricals()`).\n- Use compression when writing `.h5ad` (e.g., `compression=\"gzip\"`) to reduce storage; consider `zarr` for chunked\/cloud-friendly access.","use_cases":["Load and inspect single-cell datasets stored as .h5ad files.","Combine multiple experiments or batches into a unified object.","Work with large, sparse count matrices without loading everything into memory."],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/aipoch\/medical-research-skills\/blob\/686e09dfdb45d9fa1a08664f06bb93769b3c9d91\/scientific-skills\/Data%20Analysis\/anndata\/SKILL.md","source_commit":"686e09dfdb45d9fa1a08664f06bb93769b3c9d91","license":"MIT","version":null,"listing_approved_at":"2026-11-24","created_at":"2026-11-23T10:57:13.000000Z","updated_at":"2026-11-24T07:14:40.000000Z","seo_title":"Anndata for Single-Cell Data Management","seo_description":"Anndata is a data structure for annotated matrices in single-cell analysis. Use it for reading\/writing .h5ad files and working with the scverse ecosystem.","seo_keywords":["single-cell data management","h5ad file handling","scverse ecosystem","annotated matrices","sparse matrix operations"]}}