Written and maintained by CASRAI Editorial Board
Published
On this page
scikit-bio (skbio) is an open-source Python library providing specialized data structures, mathematical algorithms, and statistical workflows for bioinformatics and omic data analysis. Released under a permissive BSD 3-Clause license, scikit-bio bridges general-purpose scientific computing libraries like NumPy, pandas, and SciPy with specialized domain applications in microbiome diversity, phylogenetics, molecular sequence manipulation, and ecological multivariate statistics.
What it is used for in research
In biological research, high-throughput sequencing generates multidimensional datasets that demand specialized mathematical processing. While general data science packages offer standard matrix operations, biological data exhibits unique properties: non-Euclidean distance relationships, phylogenetic dependencies, high sparsity, and constant-sum constraints of relative abundance tables. The scikit-bio library provides a unified, performant foundation for addressing these computational challenges within Python.
The library originated from codebases developed within PyCogent and the Quantitative Insights Into Microbial Ecology (QIIME) project. Under lead developers Dr. Qiyun Zhu at Arizona State University, Dr. James Morton at Gutz Analytics, and Dr. Daniel McDonald at UC San Diego, alongside advisors Dr. Rob Knight and Dr. Greg Caporaso, scikit-bio evolved into an independent library supported by the U.S. Department of Energy (DOE Award DE-SC0024320). Its formal methodology is published in Nature Methods (Aton et al., 2025). The package serves as the underlying statistical engine for QIIME 2, Qiita, and the Emperor 3D ordination viewer.
Researchers utilize scikit-bio across several primary analytical domains:
- Molecular sequence manipulation: Storing, validating, and transforming DNA, RNA, and protein sequences using IUPAC-compliant alphabets via
skbio.sequence. It supports reverse complements, transcription, translation, and k-mer frequency profiling. - Sequence alignment: Computing global and local pairwise alignments using preset scoring schemes (
pair_align_nucl,pair_align_prot) and managing multiple sequence alignments withTabularMSA. - Phylogenetic reconstruction and traversal: Manipulating hierarchical tree structures through
TreeNodeinskbio.tree. Researchers construct distance trees using neighbor-joining (NJ) or UPGMA, root trees at midpoints, calculate tip-to-tip patristic distances, and resolve polytomies. - Ecological community diversity: Calculating alpha diversity (within-sample richness and evenness) and beta diversity (between-sample compositional dissimilarity) across microbial communities via
skbio.diversity. - Multivariate ordination and hypothesis testing: Running Principal Coordinates Analysis (PCoA) via
skbio.stats.ordination.pcoa, and testing group differentiation non-parametrically using PERMANOVA, ANOSIM, and Mantel matrix tests inskbio.stats.distance. - Compositional data analysis: Implementing log-ratio transformations (Centered Log-Ratio, Isometric Log-Ratio) and differential abundance testing (ANCOM) to overcome false-discovery artifacts common in marker-gene and shotgun metagenomic datasets.
- Biological embeddings: Integrating vector representations from protein language models (pLMs) through
skbio.embedding, linking modern deep learning representations to downstream ecological and evolutionary statistics.
Unlike general-purpose molecular libraries such as Biopython, which emphasizes sequence file parsing, GenBank record querying, and structural PDB manipulation, scikit-bio focuses heavily on community ecology, phylogenetic math, and multivariate statistical modeling for multiomic research.
Install or access
scikit-bio supports 64-bit Linux (x86_64, ARM64), macOS (Intel, Apple Silicon), and 64-bit Windows. The 0.7.x release series requires Python 3.10 or later, with Python 3.11 or 3.12 recommended. Because scikit-bio relies on compiled Cython extensions, C/C++ libraries, and optimized linear algebra routines, package management via Conda or Mamba is the recommended route.
Installing via Conda or Mamba
Official community builds are hosted on the conda-forge channel. When configuring a bioinformatics environment, choosing Mamba vs Conda provides substantially faster dependency resolution when assembling complex environments containing HDF5 and BLAS libraries. Run the following command in your terminal:
conda install -c conda-forge scikit-bio
Installing via PyPI
Alternatively, pre-compiled binary wheels are distributed for common platforms on PyPI. To install scikit-bio into an active virtual environment using pip, run:
pip install scikit-bio
System package managers
Third-party packages exist in distribution repositories, such as Debian and Ubuntu (sudo apt install python3-skbio) or Arch Linux AUR (yay -S python-scikit-bio). However, because distribution packages often lag behind official releases, research teams should prefer Conda or PyPI wheels to ensure access to modern API features.
Verifying the installation
After installation, verify that the module loads and reports its version string without warnings:
import skbio
print(skbio.__version__)
To run the internal unit test suite across installed components, install pytest and invoke the test runner:
pip install pytest
python -m skbio.test
Hardware acceleration and computational engines
scikit-bio incorporates multiple mechanisms to accelerate computationally demanding tasks:
- OpenMP multi-threading: Compute-intensive Cython loops utilize OpenMP to parallelize across CPU cores. To build from source on systems lacking native OpenMP toolchains (such as default macOS clang), compile with
DISABLE_OPENMP=1 pip install scikit-bio --no-binary scikit-bio. - Numba JIT and GPU acceleration: Several algorithms provide optional Numba backends. Installing Numba (
pip install numba) enables just-in-time compilation, while GPU execution on NVIDIA hardware can be activated viapip install numba-cuda-mlir. - Binary acceleration package: For production pipelines, the companion package
scikit-bio-binariesprovides high-performance C++ routines, installable viaconda install -c conda-forge scikit-bio-binaries.
Step-by-step task: Microbiome diversity and ordination workflow
This walkthrough demonstrates an end-to-end community analysis. We will load sample feature counts, compute alpha diversity, evaluate phylogenetic and non-phylogenetic beta diversity, conduct dimensionality reduction via PCoA, and test group differences using PERMANOVA.
Step 1: Set up sample data, metadata, and phylogenetic tree
In standard microbiome studies, input data comprises a feature abundance table (ASVs or OTUs across samples), a sample metadata table defining experimental cohorts, and a rooted phylogenetic tree relating the taxa. We initialize these structures using pandas, NumPy, and scikit-bio:
import numpy as np
import pandas as pd
import skbio
from skbio.tree import TreeNode
from skbio.diversity import alpha_diversity, beta_diversity
from skbio.stats.ordination import pcoa
from skbio.stats.distance import permanova
# Construct count matrix: 6 samples across 5 microbial taxa
sample_ids = ['Sample_1', 'Sample_2', 'Sample_3', 'Sample_4', 'Sample_5', 'Sample_6']
taxa_ids = ['Taxon_A', 'Taxon_B', 'Taxon_C', 'Taxon_D', 'Taxon_E']
counts = np.array([
[120, 45, 0, 0, 15], # Control group
[110, 50, 5, 0, 10], # Control group
[135, 40, 0, 2, 18], # Control group
[ 10, 5, 95, 80, 60], # Treatment group
[ 5, 0, 110, 75, 55], # Treatment group
[ 12, 8, 85, 90, 70] # Treatment group
])
table = pd.DataFrame(counts, index=sample_ids, columns=taxa_ids)
# Sample metadata: defining experimental treatment
metadata = pd.DataFrame({
'Group': ['Control', 'Control', 'Control', 'Treated', 'Treated', 'Treated'],
'Batch': [1, 2, 1, 2, 1, 2]
}, index=sample_ids)
# Define a rooted phylogenetic tree in Newick format and parse with TreeNode
newick_str = "((Taxon_A:0.1,Taxon_B:0.15):0.2,(Taxon_C:0.05,(Taxon_D:0.2,Taxon_E:0.25):0.1):0.3);"
tree = TreeNode.read([newick_str], format='newick')
tree.root_at_midpoint()
Step 2: Calculate within-sample alpha diversity
Alpha diversity measures the richness and evenness of taxa within each individual sample. We compute both Shannon entropy and Faith’s Phylogenetic Diversity. The theoretical foundations of richness and evenness can be referenced in guides detailing the Shannon Diversity Index and species evenness.
# Calculate Shannon diversity index across samples
shannon_series = alpha_diversity('shannon', table, ids=sample_ids)
print("Shannon Entropy:")
print(shannon_series)
# Calculate Faith's Phylogenetic Diversity incorporating tree branch lengths
faith_series = alpha_diversity('faith_pd', table, ids=sample_ids, otu_ids=taxa_ids, tree=tree)
print("nFaith's Phylogenetic Diversity (PD):")
print(faith_series)
Step 3: Compute between-sample beta diversity matrices
Beta diversity quantifies compositional dissimilarity between pairs of biological communities. We compute Bray-Curtis dissimilarity and Weighted UniFrac:
# Bray-Curtis dissimilarity (taxonomic counts only)
bc_dm = beta_diversity('bray_curtis', table, ids=sample_ids)
print("Bray-Curtis Distance Matrix:")
print(bc_dm)
# Weighted UniFrac (accounting for phylogenetic tree topology and branch lengths)
unifrac_dm = beta_diversity('weighted_unifrac', table, ids=sample_ids, otu_ids=taxa_ids, tree=tree)
print("nWeighted UniFrac Distance Matrix:")
print(unifrac_dm)
Step 4: Perform Principal Coordinates Analysis (PCoA)
To visualize sample relationships in low-dimensional space, we perform Principal Coordinates Analysis (PCoA) on the distance matrix:
# Run PCoA ordination on the Weighted UniFrac distance matrix
ordination = pcoa(unifrac_dm)
# View explained variance per principal coordinate
print("Proportion of Variance Explained:")
print(ordination.proportion_explained)
# View sample projection coordinates on leading axes
coords = ordination.samples[['PC1', 'PC2']]
print("nSample Coordinates (PC1 and PC2):")
print(coords)
Step 5: Test group hypotheses with PERMANOVA
To evaluate whether clustering between Control and Treated cohorts is statistically significant, we execute a non-parametric Permutational Multivariate Analysis of Variance (PERMANOVA) with 999 permutations:
# Run PERMANOVA on Weighted UniFrac distances using the 'Group' metadata factor
perm_result = permanova(unifrac_dm, grouping=metadata['Group'], permutations=999)
print("PERMANOVA Statistical Results:")
print(perm_result)
Step 6: Manipulate and query the phylogenetic tree
In addition to diversity driver functions, skbio.tree.TreeNode provides programmatic methods to inspect topological distances and branch properties:
# Compute pairwise patristic distances between tree tips
tip_dm = tree.tip_to_tip_distances()
print("Phylogenetic Tip-to-Tip Distance Matrix:")
print(tip_dm)
# Find the lowest common ancestor (LCA) for selected taxa
lca_node = tree.lowest_common_ancestor(['Taxon_C', 'Taxon_D'])
print(f"nLCA of Taxon_C and Taxon_D has {len(list(lca_node.tips()))} descendant tips.")
Output and how to read it
Understanding the programmatic output returned by scikit-bio functions is critical for drawing valid scientific conclusions.
Alpha diversity series
The alpha_diversity driver returns a pandas.Series indexed by sample identifiers. For Shannon entropy, values represent community information content: higher values indicate greater richness and evenness, whereas low values indicate dominance by few taxa. Faith’s PD values reflect cumulative branch lengths on the phylogenetic tree; a community containing distantly related lineages yields a substantially larger Faith’s PD value than one containing closely related congeneric species.
DistanceMatrix objects
Beta diversity functions return an instance of skbio.stats.distance.DistanceMatrix. Key properties include:
DistanceMatrix.data: A symmetric, two-dimensional NumPy array where entry (i, j) represents pairwise distance between sample i and sample j. Diagonal elements are strictly 0.0.DistanceMatrix.ids: A tuple of string identifiers corresponding to row and column ordering.- Indexing: The object supports label-based lookup (such as
dm['Sample_1', 'Sample_4']) as well as conditional row extraction.
OrdinationResults structure
The pcoa function returns an OrdinationResults container containing several key components:
proportion_explained: A pandas Series indicating the fraction of total matrix variance captured by each principal coordinate. For example, if PC1 captures 0.72 (72%) and PC2 captures 0.18 (18%), the two-dimensional plot represents 90% of total community variation.samples: A pandas DataFrame containing coordinate positions of each sample across all calculated axes. Researchers plot PC1 versus PC2 to inspect clustering across cohorts.eigvals: Eigenvalues corresponding to each coordinate. When using non-Euclidean ecological distances, small negative eigenvalues may appear; scikit-bio reports positive variance components for leading axes.
PERMANOVA test results
The permanova function returns a pandas Series reporting four primary metrics:
method name: Permutational Multivariate Analysis of Variance.sample size: Total number of observations included in the test.number of groups: Distinct factor levels tested (2 for Control vs Treated).test statistic: The pseudo-F ratio, measuring the ratio of between-group sum of squares to within-group sum of squares. Higher pseudo-F values indicate stronger separation between groups relative to within-group variation.p-value: Permutation-derived empirical probability of observing a pseudo-F statistic as extreme as calculated under the null hypothesis. A p-value below 0.05 indicates statistically significant compositional differentiation.
Troubleshooting
When executing bioinformatics pipelines with scikit-bio, researchers commonly encounter configuration, numerical, or data-formatting issues. Here are diagnostic procedures and solutions:
1. TreeMissingTaxaError or missing tip identifiers during UniFrac
Symptom: Calling beta_diversity('weighted_unifrac', ...) raises an exception indicating that taxa present in the count table do not exist as leaf nodes in the phylogenetic tree.
Cause: Inconsistencies between table column headers and tree tip labels, often caused by trailing whitespace or prefix mismatches.
Solution: Verify that the set of feature identifiers in your count table is a subset of the tree’s tip names before calculating diversity:
tree_tips = {tip.name for tip in tree.tips()}
missing_taxa = set(table.columns) - tree_tips
if missing_taxa:
table = table.loc[:, [col for col in table.columns if col in tree_tips]]
2. Negative eigenvalues during Principal Coordinates Analysis
Symptom: pcoa issues a runtime warning regarding negative eigenvalues, or downstream visualizations display distorted coordinate spacings.
Cause: Ecological dissimilarity metrics like Bray-Curtis and unweighted UniFrac are semi-metric or non-Euclidean, violating the triangle inequality in Euclidean space.
Solution: Taking the square root of the distance matrix prior to ordination (np.sqrt(dm.data)) often reduces non-Euclidean distortion, or researchers can apply Lingoes or Cailliez metric multidimensional scaling adjustments.
3. Undefined mathematical operations in compositional transformations
Symptom: Calling skbio.stats.composition.clr raises errors or produces arrays filled with NaN or infinite values.
Cause: Microbiome count tables contain abundant zero counts. Logarithms of zero are mathematically undefined.
Solution: Apply a multiplicative pseudocount replacement strategy before log-ratio transformation using scikit-bio’s dedicated utility:
from skbio.stats.composition import multiplicative_replacement, clr
non_zero_table = multiplicative_replacement(table.values)
clr_transformed = clr(non_zero_table)
4. OpenMP build failures on macOS Apple Silicon
Symptom: Compiling scikit-bio from source fails with compiler errors indicating missing -fopenmp support.
Cause: Default Apple Clang compilers shipped with Xcode do not include OpenMP runtime libraries.
Solution: Install LLVM OpenMP via Homebrew (brew install libomp) and export compiler flags before building, or install scikit-bio via pre-compiled conda-forge binaries.
5. Memory exhaustion during large pairwise distance calculations
Symptom: Computing beta diversity across tens of thousands of samples causes out-of-memory process termination.
Cause: A dense DistanceMatrix scales quadratically: 50,000 samples require a float64 array of 2.5 billion cells (~20 GB RAM) for matrix storage alone.
Solution: Utilize scikit-bio’s binary acceleration routines, perform sample rarefaction using skbio.stats.subsample_counts, or compute pairwise blocks iteratively.
Free alternatives
Bioinformatics researchers have access to several open-source libraries across Python and R. Choosing the right tool depends on whether your project focuses on sequence parsing, complete workflow tracking, or statistical ordination.
| Package | Primary Language | Core Focus | Key Strengths | Primary Differences vs scikit-bio |
|---|---|---|---|---|
| scikit-bio | Python | Microbiome diversity, phylogenetics, ordination | Native integration with NumPy/pandas; rich distance matrix stats; compositional data analysis | Reference package; specialized in ecological and evolutionary statistics rather than general genomics |
| Biopython | Python | General molecular biology and bioinformatics | Broad format parsers (GenBank, PDB, BLAST, Entrez); extensive community adoption | Lacks dedicated community diversity (UniFrac), distance matrix hypothesis testing, and PCoA ordination |
| QIIME 2 | Python / CLI | End-to-end microbiome analysis platform | Decentralized plugin system; automated provenance tracking; interactive web visualization files | Higher container overhead; uses scikit-bio internally as its underlying algorithmic engine |
| vegan | R | Community ecology and vegetation analysis | Gold standard ordination (NMDS, CCA, RDA); flexible PERMANOVA (adonis2) |
R-exclusive; lacks native Python data structures, protein embeddings, and sequence manipulation |
| phyloseq | R / Bioconductor | Microbiome census data container and exploration | Unified S4 data container linking OTU table, taxonomy, tree, and sample metadata; ggplot2 integration | Constrained to R environment; memory-intensive on massive multi-million sequence datasets |
For research teams operating within a Python-centric data science stack, scikit-bio offers the most natural bridge between pandas DataFrames, SciPy mathematical routines, and ecological analysis. While vegan remains the benchmark in R for community ecology and bioinformatics workflows, scikit-bio provides equivalent statistical rigor with modern Python ergonomics.
The technical data table below outlines the architecture, primary classes, key functions, and computational acceleration mechanisms across each major scikit-bio module.
Frequently asked questions
How does scikit-bio differ from Biopython?
While both are open-source Python bioinformatics packages, they serve distinct analytical niches. Biopython is designed primarily for molecular sequence processing, GenBank database queries, BLAST execution, and 3D protein structure (PDB) parsing. scikit-bio, in contrast, focuses on community ecology, phylogenetics, and multivariate statistics. It provides specialized tools for calculating alpha and beta diversity, building and manipulating phylogenetic trees, executing Principal Coordinates Analysis (PCoA), and testing ecological hypotheses via PERMANOVA.
Can scikit-bio calculate UniFrac distances without a phylogenetic tree?
No. UniFrac is inherently a phylogenetic distance metric that quantifies the fraction of branch length unique to one community versus shared between communities. To calculate unweighted or weighted UniFrac in scikit-bio, you must provide a valid TreeNode object whose tip names match the feature identifiers in your abundance table. For non-phylogenetic distance calculations that do not require a tree, scikit-bio provides metrics such as Bray-Curtis, Jaccard, Euclidean, and Canberra distances.
How does scikit-bio handle compositional data in microbiome studies?
High-throughput marker gene sequencing yields relative abundance data that sums to an arbitrary total library size, introducing spurious negative correlations when analyzed with standard Pearson or Spearman statistics. scikit-bio includes a dedicated module, skbio.stats.composition, that implements the mathematical principles of compositional data analysis (CoDa). It provides multiplicative zero-replacement functions, centered log-ratio (CLR) transformations, isometric log-ratio (ILR) transformations, and the Analysis of Composition of Microbiomes (ANCOM) test.
Is scikit-bio compatible with QIIME 2 artifacts?
Yes. scikit-bio serves as a foundational dependency of the QIIME 2 platform. Data stored within QIIME 2 artifact archives (.qza files) can be exported into standard file formats (such as BIOM tables, Newick trees, and FASTA files) and directly parsed by scikit-bio. Furthermore, custom QIIME 2 plugins frequently import scikit-bio data structures directly when implementing new analytical steps.
What Python versions are supported by scikit-bio?
The modern 0.7.x release series of scikit-bio requires Python 3.10 or later, with full support for Python 3.11 and 3.12. Older Python versions (such as Python 3.8 and 3.9) are deprecated in accordance with the project’s support policy, which follows Python’s official end-of-life schedule to ensure compatibility with modern NumPy (version 2.0+) and SciPy distributions.
Sources
- scikit-bio Official Documentation: https://scikit.bio/docs/latest/ (Accessed: 2026-11-15)
- scikit-bio Installation & Architecture Guide: https://scikit.bio/install.html (Accessed: 2026-11-15)
- scikit-bio PyPI Package Metadata: https://pypi.org/pypi/scikit-bio/json (Accessed: 2026-11-15)
- Aton, M., McDonald, D., Cañardo Alastuey, J. et al. Scikit-bio: a fundamental Python library for biological omic data analysis. Nature Methods (2025): https://doi.org/10.1038/s41592-025-02981-z (Accessed: 2026-11-15)
- scikit-bio GitHub Repository: https://github.com/scikit-bio/scikit-bio (Accessed: 2026-11-15)
- scikit-bio Project Leadership & Governance: https://scikit.bio/about.html (Accessed: 2026-11-15)
Data: scikit-bio Core Modules and Analytical Capabilities
Technical specification of scikit-bio subpackages compiled from official documentation and codebase, comparing primary classes, key mathematical algorithms, biological applications, and computational engines.
| Module | Core Classes | Key Functions | Biological Domain | Accelerated Engine |
|---|---|---|---|---|
| skbio.sequence | DNA, RNA, Protein, GeneticCode | reverse_complement, transcribe, translate, iter_kmers | Molecular sequence validation, IUPAC manipulation, motif discovery | Cython / NumPy |
| skbio.alignment | TabularMSA, AlignPath, PairAlignPath | pair_align, pair_align_nucl, pair_align_prot | Pairwise and multiple sequence alignment, gap penalty modeling | Cython / OpenMP |
| skbio.tree | TreeNode | upgma, nj, gme, bme, root_at_midpoint | Phylogenetic reconstruction, Newick parsing, ancestral state analysis | Python / Cython |
| skbio.diversity.alpha | alpha_diversity | shannon, simpson, chao1, faith_pd, observed_otus | Within-community diversity, species richness, evenness estimation | Cython / Numba |
| skbio.diversity.beta | beta_diversity | bray_curtis, jaccard, unweighted_unifrac, weighted_unifrac | Between-community dissimilarity, phylogenetic distance metrics | Cython / OpenMP / Numba |
| skbio.stats.ordination | OrdinationResults | pcoa, cca, rda | Dimensionality reduction, ecological gradient visualization | SciPy / NumPy linalg |
| skbio.stats.distance | DistanceMatrix, DissimilarityMatrix | permanova, anosim, mantel, bioenv | Non-parametric multivariate hypothesis testing | Cython / OpenMP |
| skbio.stats.composition | Table | clr, ilr, alr, multiplicative_replacement, ancom | Compositional data analysis for relative abundance tables | NumPy / SciPy |
| skbio.embedding | SequenceEmbedding, ProteinEmbedding | embed_vec_to_numpy | Protein language model vector representations and downstream stats | NumPy / PyTorch |
| skbio.io | Format Registry | read, write | Standard I/O for FASTA, FASTQ, Newick, BIOM, QSeq, GenBank | Python / C parsers |
Sources
- scikit-bio 0.7.4 Documentation (accessed 2026-11-15)
- Nature Methods scikit-bio Publication (accessed 2026-11-15)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







