Skip to content

NumPy Essentials

NumPy stores numeric data in arrays and applies operations to their elements. SciPy and scikit-learn accept these arrays, and pandas can expose numeric columns as arrays. The array has no gene or sample labels, so its shape and axis order must carry that information.

This lesson uses an invented count vector and an expression matrix. It follows the calculations through dtype conversion, selection, and centering so you can see which operation changes the values or the original object.

Download the English captions for this video.

Use a uv project with NumPy installed. Save the Python blocks in page order as numpy_essentials.py, then run uv run python numpy_essentials.py from that project. The output blocks show the printed results and do not belong in the Python file.

The count vector contains one integer per gene. The explicit int64 dtype chooses a fixed integer width instead of relying on the platform default.

import numpy as np
np.set_printoptions(precision=3, suppress=True)
counts = np.array([120, 455, 89, 1200, 33], dtype=np.int64)
print("Counts:", counts)
print("Shape:", counts.shape)
print("Dtype:", counts.dtype)
print("Dimensions:", counts.ndim)
Counts: [ 120 455 89 1200 33]
Shape: (5,)
Dtype: int64
Dimensions: 1

The next array uses rows for genes and columns for samples. Other libraries can use the opposite orientation, so state that convention before an axis reduction.

expr = np.array([
[5.1, 6.3, 2.2, 2.8],
[0.4, 0.9, 7.7, 8.1],
[3.3, 3.1, 3.4, 3.2],
])
print("Expression shape:", expr.shape)
print("Zero vector:", np.zeros(3))
print("Integer range:", np.arange(0, 10, 2))
print("Even spacing:", np.linspace(0, 1, 5))
Expression shape: (3, 4)
Zero vector: [0. 0. 0.]
Integer range: [0 2 4 6 8]
Even spacing: [0. 0.25 0.5 0.75 1. ]

arange excludes its stop value. linspace includes both endpoints by default and takes the number of values, rather than a step size.

An array has one dtype. Assigning a float to an integer array converts that value to the array’s existing type, which removes its fractional part here.

integers = np.array([1, 2, 3], dtype=np.int64)
integers[0] = 9.99
print("Integer assignment:", integers)
floats = integers.astype(float)
floats[0] = 9.99
print("Float assignment:", floats)
Integer assignment: [9 2 3]
Float assignment: [9.99 2. 3. ]

NumPy’s fixed-width integer arrays can overflow. These array additions wrap within the int8 range, unlike arithmetic on Python’s built-in integers.

small_counts = np.array([120], dtype=np.int8)
increment = np.array([10], dtype=np.int8)
print("int8 maximum:", np.iinfo(np.int8).max)
print("int8 array sum:", small_counts + increment)
print("Python integer sum:", 120 + 10)
int8 maximum: 127
int8 array sum: [-126]
Python integer sum: 130

Mixing integers and floats selects a floating dtype in this example. Mixing integers and text produces a Unicode array instead. That array does not acquire numeric meaning because its strings look like numbers.

mixed_numeric = np.array([1, 2.5, 3])
mixed_text = np.array([1, "2", 3])
print("Numeric dtype:", mixed_numeric.dtype)
print("Text dtype kind:", mixed_text.dtype.kind)
print("Text values:", mixed_text)
try:
mixed_text.sum()
except TypeError as error:
print("Text reduction rejected:", type(error).__name__)
print("Converted total:", mixed_text.astype(float).sum())
Numeric dtype: float64
Text dtype kind: U
Text values: ['1' '2' '3']
Text reduction rejected: TypeError
Converted total: 6.0

The conversion raises ValueError if a string cannot represent a number. Inspect the dtype before an arithmetic operation, then decide whether conversion matches the meaning of the input column.

Multiplication and log2 operate on each element without a Python loop. The logarithm uses a pseudocount of one so zero counts would have a finite result.

print("Doubled counts:", counts * 2)
print("Log2 counts plus one:", np.log2(counts + 1))
Doubled counts: [ 240 910 178 2400 66]
Log2 counts plus one: [ 6.919 8.833 6.492 10.23 5.087]

For this single sample, counts per million divide each count by the total count and multiply by one million. The total must be positive; an empty or all-zero sample cannot supply this denominator.

library_size = counts.sum()
if library_size <= 0:
raise ValueError("the library must have a positive count total")
cpm = counts / library_size * 1e6
print("CPM:", np.round(cpm, 1))
print("CPM total:", round(float(cpm.sum()), 6))
CPM: [ 63257.8 239852.4 46916.2 632577.8 17395.9]
CPM total: 1000000.0

This vector contains finite, nonnegative counts. The testing lesson defines checks for inputs that violate those requirements.

For this gene-by-sample matrix, axis=0 reduces the gene rows and leaves one value per sample. axis=1 reduces the sample columns and leaves one value per gene.

sample_means = expr.mean(axis=0)
gene_means_flat = expr.mean(axis=1)
print("Per-sample means:", sample_means)
print("Per-gene means:", gene_means_flat)
print("Mean shapes:", sample_means.shape, gene_means_flat.shape)
Per-sample means: [2.933 3.433 4.433 4.7 ]
Per-gene means: [4.1 4.275 3.25 ]
Mean shapes: (4,) (3,)

A nonsquare matrix helps expose a reversed axis because the two reductions produce different lengths. The shape alone cannot identify an axis mistake on a square matrix.

A comparison produces a Boolean array. Apply that array inside square brackets to retrieve the counts that pass the condition. Summing the mask counts its True elements.

mask = counts > 100
print("Mask:", mask)
print("Selected counts:", counts[mask])
print("Number selected:", mask.sum())
Mask: [ True True False True False]
Selected counts: [ 120 455 1200]
Number selected: 3

Combine array conditions with & or | and put parentheses around each comparison. The combined mask and the selected counts are different arrays.

within_range = (counts > 100) & (counts < 1000)
print("Combined mask:", within_range)
print("Counts in range:", counts[within_range])
print("Labels:", np.where(counts > 100, "high", "low"))
Combined mask: [ True True False False False]
Counts in range: [120 455]
Labels: ['high' 'high' 'low' 'high' 'low']

Python’s and asks for the truth value of each entire operand. It does not combine these comparisons element by element.

try:
invalid_mask = (counts > 100) and (counts < 1000)
except ValueError as error:
print("Array truth test rejected:", type(error).__name__)
Array truth test rejected: ValueError

NumPy compares dimensions from the right. Dimensions are compatible when they are equal or one has length one; a missing leading dimension behaves as length one. These rules allow a column of gene means to align with every sample column.

gene_means = expr.mean(axis=1, keepdims=True)
centered = expr - gene_means
print("Expression shape:", expr.shape)
print("Gene mean shape:", gene_means.shape)
print("Centered row means:", centered.mean(axis=1))
print("Rows centered at zero:", np.allclose(centered.mean(axis=1), 0))
Expression shape: (3, 4)
Gene mean shape: (3, 1)
Centered row means: [ 0. -0. 0.]
Rows centered at zero: True

Without keepdims, the row means form a one-dimensional array. Its length cannot match the sample dimension of this matrix, so subtraction raises an error.

try:
expr - expr.mean(axis=1)
except ValueError as error:
print("Incompatible shapes:", type(error).__name__)
Incompatible shapes: ValueError

On a square matrix, the same mistake runs. NumPy applies the computed gene means along columns instead of applying each mean across its own gene row. It does not recompute sample means.

square_expr = expr[:, :3]
wrong_centered = square_expr - square_expr.mean(axis=1)
right_centered = square_expr - square_expr.mean(axis=1, keepdims=True)
print("Wrong row means:", wrong_centered.mean(axis=1))
print("Correct row means:", right_centered.mean(axis=1))
print("Same result:", np.allclose(wrong_centered, right_centered))
Wrong row means: [ 0.933 -0.6 -0.333]
Correct row means: [ 0. 0. -0.]
Same result: False

An ordinary sum propagates NaN. nansum excludes those entries from the total, which is a different rule for missing measurements.

values = np.array([10.0, np.nan, 70.0])
print("Values:", values)
print("Ordinary sum:", values.sum())
print("Sum excluding NaN:", np.nansum(values))
print("Missing mask:", np.isnan(values))
print("NaN equals itself:", np.nan == np.nan)
print("Entirely missing sum:", np.nansum([np.nan, np.nan]))
Values: [10. nan 70.]
Ordinary sum: nan
Sum excluding NaN: 80.0
Missing mask: [False True False]
NaN equals itself: False
Entirely missing sum: 0.0

Use isnan to detect missing floating values. An entirely missing array has a nansum of zero, so a zero result does not establish that any measurement was observed. In particular, it is not a valid normalization denominator.

Basic array slicing returns a view. Assigning through that view changes the original array because both objects refer to the same data.

original = np.array([1, 2, 3, 4, 5])
view = original[1:4]
view[0] = 999
print("Original after view assignment:", original)
print("Shared memory:", np.shares_memory(original, view))
Original after view assignment: [ 1 999 3 4 5]
Shared memory: True

An explicit copy has separate numeric storage. Integer-array indexing and Boolean indexing also return copies when retrieving values.

original = np.array([1, 2, 3, 4, 5])
copied = original[1:4].copy()
copied[0] = 999
indexed = original[[1, 3]]
indexed[0] = 888
filtered = original[original > 2]
filtered[0] = 777
print("Original after copy assignments:", original)
print("Slice copy shares memory:", np.shares_memory(original, copied))
print("Index copy shares memory:", np.shares_memory(original, indexed))
print("Mask copy shares memory:", np.shares_memory(original, filtered))
Original after copy assignments: [1 2 3 4 5]
Slice copy shares memory: False
Index copy shares memory: False
Mask copy shares memory: False

Assignment directly to original[mask] still changes original; retrieving a selection first and modifying that separate array has different behavior. A Python list slice copies its outer list, but contained lists remain shared. The array interview lesson demonstrates that nested-list case.

Create a generator with a seed and pass it to the calculation that needs random values. A new generator with the same seed reproduces this sequence in the same NumPy environment.

rng = np.random.default_rng(42)
sampled_counts = rng.poisson(100, size=5)
repeated_counts = np.random.default_rng(42).poisson(100, size=5)
print("Sampled counts:", sampled_counts)
print(
"Repeated sequence matches:",
np.array_equal(sampled_counts, repeated_counts),
)
Sampled counts: [109 112 108 87 96]
Repeated sequence matches: True

The legacy np.random.seed changes shared random state. Separate generators make that state explicit. Record the NumPy version as well as the seed when a saved result depends on an exact random sequence.

A count matrix has two gene rows and three sample columns. Its rows are [2, 0, 3] and [6, 0, 9]. Calculate a fraction for each gene within its sample. Give an all-zero sample a column of NaN values, and leave the count matrix unchanged. Before you run the calculation, write the denominator shape and predict the first and third columns.

Open the axis, mask, and ownership checks.

The reduction removes the gene axis and retains one total per sample. Initializing the result with NaN defines the values that the where mask leaves unwritten. This exercise explicitly treats an empty sample as undefined; it does not replace missing measurements with zero.

practice_counts = np.array([[2, 0, 3], [6, 0, 9]], dtype=np.int64)
saved_counts = practice_counts.copy()
sample_totals = practice_counts.sum(axis=0, keepdims=True)
fractions = np.full(practice_counts.shape, np.nan)
np.divide(practice_counts, sample_totals, out=fractions,
where=sample_totals > 0)
expected_fractions = np.array([[0.25, np.nan, 0.25],
[0.75, np.nan, 0.75]])
np.testing.assert_allclose(fractions, expected_fractions, equal_nan=True)
np.testing.assert_array_equal(practice_counts, saved_counts)
print("Denominator shape:", sample_totals.shape)
print("Fractions:")
print(fractions)
Denominator shape: (1, 3)
Fractions:
[[0.25 nan 0.25]
[0.75 nan 0.75]]

Both defined columns sum to one. A row reduction would divide each gene across samples and answer a different question.

Select the first and third columns of the same matrix into a new object. Replace every selected value with -1 without changing the original. Then explain what would happen if you selected the first two columns with a basic slice instead.

Open the selection checks.
selected_samples = practice_counts[:, [0, 2]]
selected_samples[:] = -1
np.testing.assert_array_equal(practice_counts, saved_counts)
print("Separate selected values:")
print(selected_samples)
print("Advanced selection shares memory:",
np.shares_memory(practice_counts, selected_samples))
print("Basic slice shares memory:",
np.shares_memory(practice_counts, practice_counts[:, :2]))
Separate selected values:
[[-1 -1]
[-1 -1]]
Advanced selection shares memory: False
Basic slice shares memory: True

The integer index list produces a copy. The basic slice shares storage, so assignment through that slice would change the original matrix. Add .copy() when you need a separate object from a basic slice.

Task Call
Inspect shape, dtype, and dimensions array.shape, array.dtype, array.ndim
Convert numeric storage array.astype(float)
Reduce rows or columns array.mean(axis=0), array.mean(axis=1)
Preserve the reduced dimension array.mean(axis=1, keepdims=True)
Select with a mask array[array > threshold]
Count matches (array > threshold).sum()
Choose one value per element np.where(condition, first, second)
Detect missing floating values np.isnan(array)
Sum while excluding NaN np.nansum(array)
Copy numeric storage array.copy()
Create a random generator np.random.default_rng(seed)

Read Pandas Essentials for labeled tables and column operations. The testing lesson uses known answers and invalid inputs to check a numerical function.

Harris and colleagues, 2020 describe array programming with NumPy.

The NumPy quickstart explains array attributes, creation, and reductions. Compare its axis examples with the gene and sample dimensions used here.

The broadcasting guide states the shape compatibility rules. It explains why the column of gene means can be subtracted from every sample column.

The indexing guide distinguishes basic slicing from advanced indexing. Use that distinction before you modify an array obtained from another array.

The random compatibility policy explains the limits of reproducibility across versions and environments. A seed alone does not specify the complete execution environment.

The divide reference explains the out and where arguments. When a condition is false, the corresponding output entry keeps its existing value, which is why the practice result starts with NaN.