NumPy
Most examples here use one count matrix of six genes by four samples, small enough that each output fits beside its call. The page ran with NumPy 2.5. For the reasons behind axes, dtypes, and views, read NumPy Essentials; this page only lists the calls.
Quick reference
Section titled “Quick reference”| Task | Call |
|---|---|
| Shape, dimensions, type | a.shape, a.ndim, a.dtype |
| Change type | a.astype(np.float32) |
| Reshape | a.reshape(3, -1), a.T, a.ravel() |
| Filter rows | a[mask] |
| Block by position | a[np.ix_(rows, cols)] |
| Indices where true | np.where(cond), np.flatnonzero(cond) |
| Choose per element | np.where(cond, x, y) |
| Match a list | np.isin(a, values) |
| Log transform and back | np.log1p(a), np.expm1(a) |
| Compare floats | np.isclose(a, b), np.allclose(a, b) |
| Per sample, per gene | a.sum(axis=0), a.mean(axis=1) |
| Sample standard deviation | a.std(ddof=1) |
| Quantiles | np.quantile(a, 0.75, axis=0), np.percentile(a, 75) |
| Keep dims for broadcasting | a.mean(axis=1, keepdims=True) |
| Cap values | np.clip(a, -2, 2) |
| Order and top k | np.argsort(x)[::-1][:k] |
| Skip NaN | np.nanmean, np.nansum, np.isnan |
| Join | np.concatenate, np.vstack, np.stack |
| Unique with counts | np.unique(a, return_counts=True) |
| Seeded generator | rng = np.random.default_rng(42) |
| Correlate columns | np.corrcoef(a, rowvar=False) |
| Matrix product | a @ b |
| Symmetric eigen | np.linalg.eigh(m) |
| SVD | np.linalg.svd(m, full_matrices=False) |
| Save, load | np.save, np.load, np.savetxt, np.loadtxt |
Two samples are controls and two are treated. EGFR goes up fourfold under treatment and MYC drops to a quarter, so the fold changes later on the page have something to find.
import numpy as np
np.set_printoptions(precision=3, suppress=True)rng = np.random.default_rng(42)
genes = np.array(["TP53", "BRCA1", "EGFR", "MYC", "GAPDH", "ACTB"])samples = np.array(["ctrl_1", "ctrl_2", "trt_1", "trt_2"])base = np.array([50, 20, 200, 80, 1000, 900])effect = np.array([1, 1, 4, 0.25, 1, 1])lam = np.column_stack([base, base, base * effect, base * effect])counts = rng.poisson(lam)print(counts)[[ 56 59 56 41] [ 18 22 19 21] [ 215 211 824 797] [ 69 75 20 14] [ 973 994 1019 1035] [ 890 916 871 927]]Create arrays
Section titled “Create arrays”print(np.zeros((2, 3)))print(np.ones(3, dtype=int))print(np.full((2, 2), np.nan))print(np.arange(0, 10, 2))print(np.linspace(0, 1, 5))[[0. 0. 0.] [0. 0. 0.]][1 1 1][[nan nan] [nan nan]][0 2 4 6 8][0. 0.25 0.5 0.75 1. ]Inspect shape and type
Section titled “Inspect shape and type”print(counts.shape, counts.ndim, counts.size, counts.dtype)print(counts.astype(np.float32).dtype)(6, 4) 2 24 int64float32Reshape and transpose
Section titled “Reshape and transpose”-1 tells NumPy to work out the length of that axis.
flat = np.arange(12)print(flat.reshape(3, 4))print(flat.reshape(-1, 6).shape)print(counts.T.shape)print(counts.ravel()[:6])[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]](2, 6)(4, 6)[56 59 56 41 18 22]Index and slice
Section titled “Index and slice”Rows are genes and columns are samples, so counts[gene, sample] reads in that order.
print(counts[0, 1]) # TP53 in ctrl_2print(counts[2]) # EGFR in every sampleprint(counts[:, -1]) # every gene in trt_2print(counts[1:3, :2]) # BRCA1 and EGFR in the two controls59[215 211 824 797][ 41 21 797 14 1035 927][[ 18 22] [215 211]]Filter with a boolean mask
Section titled “Filter with a boolean mask”A mask over the rows keeps the genes whose mean count passes a threshold. mask.sum()
counts how many passed.
expressed = counts.mean(axis=1) > 100print(genes[expressed])print(counts[expressed])print(expressed.sum())['EGFR' 'GAPDH' 'ACTB'][[ 215 211 824 797] [ 973 994 1019 1035] [ 890 916 871 927]]3Select a block by position
Section titled “Select a block by position”Two index lists pair up element by element. Wrap them in np.ix_ to get the block of
rows by columns instead.
print(counts[[0, 2], [0, 2]]) # two values: (0, 0) and (2, 2)print(counts[np.ix_([0, 2], [0, 2])]) # 2 x 2 block: TP53, EGFR x ctrl_1, trt_1[ 56 824][[ 56 56] [215 824]]Find positions with np.where
Section titled “Find positions with np.where”With one argument np.where returns a tuple of index arrays. With three it chooses a
value per element.
pvalues = np.array([0.001, 0.15, 0.03, 0.45, 0.01, 0.8])print(np.where(pvalues < 0.05))print(np.flatnonzero(pvalues < 0.05))print(np.where(pvalues < 0.05, "sig", "ns"))(array([0, 2, 4]),)[0 2 4]['sig' 'ns' 'sig' 'ns' 'sig' 'ns']Match against a list
Section titled “Match against a list”np.isin replaces np.in1d, which NumPy 2.5 no longer has.
panel = ["EGFR", "MYC", "KRAS"]print(np.isin(genes, panel))print(genes[~np.isin(genes, panel)])[False False True True False False]['TP53' 'BRCA1' 'GAPDH' 'ACTB']Element-wise math
Section titled “Element-wise math”log_counts = np.log2(counts + 1)print(log_counts)[[ 5.833 5.907 5.833 5.392] [ 4.248 4.524 4.322 4.459] [ 7.755 7.728 9.688 9.64 ] [ 6.129 6.248 4.392 3.907] [ 9.928 9.959 9.994 10.017] [ 9.799 9.841 9.768 9.858]]Log transform with log1p
Section titled “Log transform with log1p”np.log1p(x) is the natural log of 1 + x, the transform Scanpy applies to normalized
counts. np.expm1 undoes it.
ln_counts = np.log1p(counts)print(ln_counts[:2])print(np.expm1(ln_counts[:2]))[[4.043 4.094 4.043 3.738] [2.944 3.135 2.996 3.091]][[56. 59. 56. 41.] [18. 22. 19. 21.]]Near zero, log1p keeps digits that np.log(1 + x) loses to rounding.
print(np.log(1 + 1e-12), np.log1p(1e-12))1.000088900581841e-12 9.999999999995e-13Compare floats
Section titled “Compare floats”Floating point sums rarely match a literal exactly, so == fails where np.isclose
passes. np.allclose asks the same question of a whole array at once.
print(0.1 + 0.2 == 0.3, np.isclose(0.1 + 0.2, 0.3))print(np.array_equal(np.expm1(np.log1p(counts)), counts))print(np.allclose(np.expm1(np.log1p(counts)), counts))False TrueFalseTrueLog fold change between groups
Section titled “Log fold change between groups”ctrl_mean = log_counts[:, :2].mean(axis=1)trt_mean = log_counts[:, 2:].mean(axis=1)log2fc = trt_mean - ctrl_meanfor gene, lfc in zip(genes, log2fc): print(f"{gene:6s}{lfc:7.2f}")TP53 -0.26BRCA1 0.00EGFR 1.92MYC -2.04GAPDH 0.06ACTB -0.01NumPy 2 prints a scalar inside a list or a dict with its type, so an older tutorial that
showed [2.01] now shows [np.float64(2.01)]. Call .tolist() for plain Python numbers.
print(log2fc.max())print([log2fc.max()])print(log2fc.round(2).tolist())1.922843644314428[np.float64(1.922843644314428)][-0.26, 0.0, 1.92, -2.04, 0.06, -0.01]Summarize along an axis
Section titled “Summarize along an axis”axis=0 runs down the rows and gives one value per sample. axis=1 runs across the
columns and gives one value per gene.
print(counts.sum(axis=0)) # library size per sampleprint(counts.mean(axis=1)) # mean count per geneprint(counts.argmax(axis=0)) # row of the top gene in each sampleprint(genes[counts.argmax(axis=0)])[2221 2277 2809 2835][ 53. 20. 511.75 44.5 1005.25 901. ][4 4 4 4]['GAPDH' 'GAPDH' 'GAPDH' 'GAPDH']NumPy’s std divides by n unless you pass ddof=1. pandas and R’s sd() divide by
n - 1, so NumPy disagrees with both on the same numbers until you set it.
print(log_counts.std(axis=1))print(log_counts.std(axis=1, ddof=1))[0.204 0.109 0.962 1.035 0.034 0.035][0.235 0.126 1.11 1.195 0.039 0.041]Quantiles and percentiles
Section titled “Quantiles and percentiles”np.quantile takes probabilities from 0 to 1 and np.percentile takes 0 to 100. The
75th percentile of each sample is the scale factor of upper quartile normalization.
print(np.quantile(counts, 0.75, axis=0))print(np.percentile(counts, [25, 50, 75], axis=0))[721.25 739.75 859.25 894.5 ][[ 59.25 63. 29. 26. ] [142. 143. 440. 419. ] [721.25 739.75 859.25 894.5 ]]Broadcast to normalize samples
Section titled “Broadcast to normalize samples”A (6, 4) matrix divided by a (4,) vector divides every row by the same four library
sizes. That gives counts per million without a loop.
lib_size = counts.sum(axis=0)cpm = counts / lib_size * 1e6print(cpm.round(0))print(cpm.sum(axis=0))[[ 25214. 25911. 19936. 14462.] [ 8104. 9662. 6764. 7407.] [ 96803. 92666. 293343. 281129.] [ 31067. 32938. 7120. 4938.] [438091. 436539. 362763. 365079.] [400720. 402284. 310075. 326984.]][1000000. 1000000. 1000000. 1000000.]Broadcast to scale genes
Section titled “Broadcast to scale genes”A per gene statistic has shape (6,). keepdims=True keeps it as (6, 1), which lines
up with the rows.
gene_mean = log_counts.mean(axis=1, keepdims=True)gene_sd = log_counts.std(axis=1, ddof=1, keepdims=True)z_scores = (log_counts - gene_mean) / gene_sdprint(z_scores.round(2))[[ 0.39 0.7 0.39 -1.48] [-1.12 1.08 -0.53 0.57] [-0.85 -0.88 0.89 0.84] [ 0.8 0.9 -0.65 -1.06] [-1.19 -0.4 0.51 1.08] [-0.43 0.6 -1.19 1.02]]Cap values with clip
Section titled “Cap values with clip”A heatmap color scale stretches to the most extreme value, so cap z-scores first. With four samples no z-score can pass 1.5, so this cap is 1; a heatmap of many samples usually caps at 2 or 3.
z_capped = np.clip(z_scores, -1.0, 1.0)print(z_scores.min().round(2), z_scores.max().round(2))print(z_capped.min(), z_capped.max())print((z_capped != z_scores).sum(), "values capped")-1.48 1.08-1.0 1.08 values cappedSort and rank
Section titled “Sort and rank”np.argsort returns the order, which then indexes any array that shares the axis.
order = np.argsort(log2fc)[::-1]print(genes[order])top_two = np.argsort(-np.abs(log2fc))[:2]print(genes[top_two], log2fc[top_two].round(2))print(np.sort(counts[:, 0]))['EGFR' 'GAPDH' 'BRCA1' 'ACTB' 'TP53' 'MYC']['MYC' 'EGFR'] [-2.04 1.92][ 18 56 69 215 890 973]Missing values
Section titled “Missing values”One NaN turns mean into NaN. The nan functions skip it.
vals = np.array([10.0, np.nan, 70.0])print(vals.mean(), np.nanmean(vals), np.nanmax(vals))print(np.isnan(vals).sum())nan 40.0 70.01Join arrays
Section titled “Join arrays”batch_two = rng.poisson(lam)print(np.concatenate([counts, batch_two], axis=1).shape) # more samplesprint(np.vstack([counts, batch_two]).shape) # more genesprint(np.stack([counts, batch_two]).shape) # new first axis(6, 8)(12, 4)(2, 6, 4)Unique values and counts
Section titled “Unique values and counts”cell_types = np.array(["T", "B", "T", "NK", "T", "B", "Mono"])values, n_cells = np.unique(cell_types, return_counts=True)print(values, n_cells)['B' 'Mono' 'NK' 'T'] [2 1 1 3]Random numbers
Section titled “Random numbers”Draw from a Generator, not from the legacy np.random.seed() and np.random.normal()
pair. rng.integers replaces np.random.randint.
print(rng.normal(loc=0, scale=1, size=3))print(rng.uniform(0, 1, 3))print(rng.integers(0, 10, 3))print(rng.poisson(5, 3))print(rng.negative_binomial(n=5, p=0.05, size=3)) # mean 95, overdispersedprint(rng.choice(genes, size=3, replace=False))print(rng.permutation(samples))[-0.95 -0.339 0.84 ][0.202 0.306 0.579][5 1 4][6 3 3][ 52 79 127]['ACTB' 'MYC' 'TP53']['ctrl_1' 'trt_2' 'ctrl_2' 'trt_1']Correlation between samples
Section titled “Correlation between samples”np.corrcoef treats rows as variables. Pass rowvar=False to correlate the columns, here
the four samples.
print(np.corrcoef(log_counts, rowvar=False).round(3))[[1. 1. 0.912 0.899] [1. 1. 0.907 0.895] [0.912 0.907 1. 0.997] [0.899 0.895 0.997 1. ]]Matrix products
Section titled “Matrix products”@ is matrix multiplication. A weight vector over the genes turns the matrix into one
score per sample, here the mean of the housekeeping genes GAPDH and ACTB, the reference
level a qPCR analysis normalizes to.
weights = np.array([0, 0, 0, 0, 0.5, 0.5])print(weights @ log_counts)print(np.dot([1.0, 2.0, 3.0], [4.0, 5.0, 6.0]))[9.864 9.9 9.881 9.937]32.0Eigenvalues and SVD
Section titled “Eigenvalues and SVD”Use np.linalg.eigh for a symmetric matrix such as a covariance matrix. It returns real
eigenvalues in ascending order, where eig gives no order.
cov = np.array([[4.0, 2.0], [2.0, 3.0]])eigenvalues, eigenvectors = np.linalg.eigh(cov)print(eigenvalues)print(np.linalg.norm([3.0, 4.0]))[1.438 5.562]5.0The SVD of the gene centered matrix, with samples as rows, is a PCA. The squared singular values give the share of variance per component.
centered = (log_counts - log_counts.mean(axis=1, keepdims=True)).Tu, s, vt = np.linalg.svd(centered, full_matrices=False)print((s**2 / (s**2).sum()).round(3))print((u * s)[:, :2].round(2)) # PC1 and PC2 score per sampleprint(vt[0].round(2)) # gene loadings on PC1[0.975 0.02 0.005 0. ][[ 1.35 0.03] [ 1.46 0.01] [-1.22 -0.3 ] [-1.59 0.27]][ 0.1 -0. -0.68 0.73 -0.02 0. ]PC1 carries 97.5 percent of the variance. It puts the two controls on one side and the two treated samples on the other, and its two largest loadings are EGFR and MYC.
Save and load
Section titled “Save and load”.npy keeps the dtype and shape exactly. A TSV is readable by other tools.
from pathlib import Path
out_dir = Path("outputs")out_dir.mkdir(exist_ok=True)np.save(out_dir / "counts.npy", counts)print(np.array_equal(np.load(out_dir / "counts.npy"), counts))np.savetxt(out_dir / "counts.tsv", counts, fmt="%d", delimiter="\t")print(np.loadtxt(out_dir / "counts.tsv", delimiter="\t", dtype=int)[:2])True[[56 59 56 41] [18 22 19 21]]Calls removed in NumPy 2
Section titled “Calls removed in NumPy 2”Code from an older tutorial stops with an AttributeError on these names.
| Old call | Use now |
|---|---|
np.float_, np.NaN, np.Inf |
np.float64, np.nan, np.inf |
np.product, np.cumproduct |
np.prod, np.cumprod |
np.alltrue, np.sometrue |
np.all, np.any |
np.round_ |
np.round |
np.in1d |
np.isin |
np.row_stack |
np.vstack |
np.trapz |
np.trapezoid |
np.asfarray(x) |
np.asarray(x, dtype=float) |
See also
Section titled “See also”- NumPy Essentials explains dtypes, axes, broadcasting, and views with the bugs each one causes.
- Vectors & Matrices covers the algebra
behind
@. - Eigenvectors, SVD & PCA derives the PCA that the SVD example computes.
- The pandas and Polars cheatsheets put labels on these arrays, and Data Wrangling works through whole table operations.
Scientific references
Section titled “Scientific references”Harris and colleagues, 2020 describe array programming with NumPy.
Further reading
Section titled “Further reading”-
The tutorial explains array shapes, indexing, broadcasting, reductions, and copies. Use its axis examples to check whether a count summary returns one value per gene or per sample.