scanpy.tl.rank_genes_groups#

scanpy.tl.rank_genes_groups(adata, groupby, *, mask=None, use_raw=None, groups='all', reference='rest', n_genes=None, rankby_abs=False, pts=False, method='t-test' (sc.settings.preset='scanpy-v1' – changes in 2.0), corr_method='benjamini-hochberg', tie_correct=False, use=None, mean_in_log_space=True (sc.settings.preset='scanpy-v1' – changes in 2.0), out=False, key_added=None, layer=None, mask_var=None, copy=False, **kwds)[source]#

Rank genes for characterizing groups.

Expects logarithmized data.

Array type support#

Array type

supported

… experimentally in dask Array

numpy.ndarray

✅

❌

scipy.sparse.{csr,csc}_{array,matrix}

✅

❌

Warning

Comparing between cells leads to highly inflated p-values, since cells are not independent observations [Squair et al., 2021]. Especially in single-cell data, consider instead to use more appropriate methods such as combining pseudobulking with PyDESeq2 documentation.

decoupler.pp.pseudobulk() or scanpy.get.aggregate() can be used to aggregate samples for pseudobulking. Ours is a bit more verbose, but supports Dask arrays for improved performance.

Parameters:
adata AnnData

Annotated data matrix.

groupby AdRef | str

The observations grouping to consider. Given by a reference like A.obs['leiden'], or by column name (strs are resolve()d with ScanpyV2Preview).

mask NDArray[bool] | AdRef[Idx2D | int, AnnData] | str | None (default: None)

Select subset of genes to use in statistical tests. Given by a boolean array or a reference to one, e.g. A.var['selected']. strs are anndata.acc.AdAcc.resolve()d, e.g. 'var.selected'.

mask_var NDArray[bool] | AdRef[Idx2D | int, AnnData] | str | None (default: None)

Deprecated since version 1.13.0: Use mask instead.

A boolean array, or a column of var named by a str, i.e. mask_var='selected' is mask=A.var['selected'].

use_raw bool | None (default: None)

Deprecated since version 1.13.0: raw is deprecated. Keep the data in a layer instead.

Use raw attribute of adata if present. The default behavior is to use raw if present.

use LayerAcc | str | None (default: None)

Which matrix to perform tests on. Given by an accessor, e.g. A.X or A.layers['counts']. strs are anndata.acc.AdAcc.resolve()d, e.g. 'layers.counts'.

layer str | None (default: None)

Deprecated since version 1.13.0: Use use instead.

A key of layers, i.e. layer='k' is use=A.layers['k'].

groups Literal['all'] | Iterable[str] (default: 'all')

Subset of groups, e.g. ['g1', 'g2', 'g3'], to which comparison shall be restricted, or 'all' (default), for all groups. Note that if reference='rest' all groups will still be used as the reference, not just those specified in groups.

reference str (default: 'rest')

If 'rest', compare each group to the union of the rest of the group. If a group identifier, compare with respect to this group.

n_genes int | None (default: None)

The number of genes that appear in the returned tables. Defaults to all genes.

method Literal['logreg', 't-test', 'wilcoxon', 'wilcoxon_illico', 't-test_overestim_var'] | Default (default: 't-test' (sc.settings.preset='scanpy-v1' – changes in 2.0))

The default method is 't-test', 't-test_overestim_var' overestimates variance of each group, 'wilcoxon' uses Wilcoxon rank-sum, 'logreg' uses logistic regression. See Ntranos et al. [2019], here and here, for why this is meaningful.

corr_method Literal['benjamini-hochberg', 'bonferroni'] (default: 'benjamini-hochberg')

p-value correction method. Used only for 't-test', 't-test_overestim_var', and 'wilcoxon'.

tie_correct bool (default: False)

Use tie correction for 'wilcoxon' scores. Used only for 'wilcoxon'.

rankby_abs bool (default: False)

Rank genes by the absolute value of the score, not by the score. The returned scores are never the absolute values.

pts bool (default: False)

Compute the fraction of cells expressing the genes.

mean_in_log_space bool | Default (default: True (sc.settings.preset='scanpy-v1' – changes in 2.0))

Whether to do log⁡(mean⁡(ex)) (False) or log⁡(emean⁡(x)) (True). The former is accurate, while the latter is a faster approximation that underestimates this accurate result in the presence of many outliers.

kwds

Are passed to test methods. Currently this affects only parameters that are passed to sklearn.linear_model.LogisticRegression. For instance, you can pass penalty='l1' to try to come up with a minimal set of genes that are good predictors (sparse solution meaning few non-zero fitted coefficients).

out bool (default: False)

Where to write the results. If True, the results is returned instead of written. If False, it is written to .uns['rank_genes_groups'].

key_added str | None (default: None)

Name of the uns entry to write to instead (until there are .uns accessors).

copy bool (default: False)

Deprecated since version 1.13.0: Copy adata before calling this function instead.

Whether to copy adata or modify it inplace.

Return type:

AnnData | dict[str, Any] | None

Returns:

Returns the results as a dict if out=True, else None. Sets the following fields:

adata.uns['rank_genes_groups' | key_added]['names']structured numpy.ndarray (dtype object)

Structured array to be indexed by group id storing the gene names. Ordered according to scores.

adata.uns['rank_genes_groups' | key_added]['scores']structured numpy.ndarray (dtype object)

Structured array to be indexed by group id storing the z-score underlying the computation of a p-value for each gene for each group. Ordered according to scores.

adata.uns['rank_genes_groups' | key_added]['logfoldchanges']structured numpy.ndarray (dtype object)

Structured array to be indexed by group id storing the log2 fold change for each gene for each group. Ordered according to scores. Only provided if method is ‘t-test’ like. Note: if mean_in_log_space=True, this is an approximation calculated from mean-log values.

adata.uns['rank_genes_groups' | key_added]['pvals']structured numpy.ndarray (dtype float)

p-values.

adata.uns['rank_genes_groups' | key_added]['pvals_adj']structured numpy.ndarray (dtype float)

Corrected p-values.

adata.uns['rank_genes_groups' | key_added]['pts']pandas.DataFrame (dtype float)

Fraction of cells expressing the genes for each group.

adata.uns['rank_genes_groups' | key_added]['pts_rest']pandas.DataFrame (dtype float)

Only if reference is set to 'rest'. Fraction of cells from the union of the rest of each group expressing the genes.

Notes

There are slight inconsistencies depending on whether sparse or dense data are passed. See here.

Examples

>>> import scanpy as sc
>>> adata = sc.datasets.pbmc68k_reduced()
>>> sc.tl.rank_genes_groups(adata, "bulk_labels", method="wilcoxon")
>>> # to visualize the results
>>> sc.pl.rank_genes_groups(adata)