Initializing playground…
← tsb playground

🕳️ SparseArray & SparseDtype

Memory-efficient storage for arrays where most values share a common fill value. Mirrors pandas.arrays.SparseArray and pandas.SparseDtype.

✅ Complete

Overview

A SparseArray stores only the non-fill values and their positions. When most elements share a common value — zeros in a sparse matrix, NaN in sensor data with many gaps, or false in a boolean feature array — sparse storage dramatically reduces memory use.

The fill_value is the implicit value for all positions not explicitly stored. Common choices are 0 (numeric zero), NaN (missing values), or false (boolean). By default tsb uses NaN (matching pandas behaviour).

💡 When to use SparseArray: when density < ~0.25 (fewer than 25% of values are non-fill). Below that threshold, sparse storage saves memory and the bookkeeping overhead is worth it.

Quick Start

TypeScript
Click ▶ Run to execute
Ctrl+Enter to run · Tab to indent

Interactive Demo

Enter a comma-separated list of numbers and choose a fill value to see how SparseArray stores your data.

API Reference

SparseArray.fromDense(data, fill_value?, subtype?)

Create a SparseArray from a dense array. Values equal to fill_value are not stored.

SparseArray.fromSparse(length, indices, values, fill_value?, subtype?)

Create a SparseArray directly from COO (Coordinate) sparse components.

Properties

PropertyTypeDescription
lengthnumberTotal logical length (including fill positions)
npointsnumberNumber of explicitly stored (non-fill) values
densitynumberFraction stored: npoints / length (0–1)
fill_valuenumberImplicit value for positions not stored
sp_valuesnumber[]Array of stored (non-fill) values
sp_indexnumber[]Positions (0-based) of stored values
dtypeSparseDtypeDescribes element type and fill value

Methods

MethodDescription
at(i)Value at index i (fill_value for fill positions)
toDense()Convert to a regular number[] array
toCoo()Return {indices, values} COO representation
fillna(value)Replace NaN values; returns new SparseArray
withFillValue(v)Change fill value; returns new SparseArray
slice(start, end?)Slice to [start, end); returns new SparseArray
add(scalar)Add a scalar to all values; returns new SparseArray
mul(scalar)Multiply by a scalar; returns new SparseArray
sum()Sum of all values (NaN-skipped)
mean()Mean of all non-NaN values
max()Maximum value (NaN-ignored)
min()Minimum value (NaN-ignored)
std(ddof?)Standard deviation (default ddof=1)

Use Cases

Sensor data with gaps

TypeScript
Click ▶ Run to execute
Ctrl+Enter to run · Tab to indent

Feature matrix (recommendation systems)

TypeScript
Click ▶ Run to execute
Ctrl+Enter to run · Tab to indent

Sparse boolean flags

TypeScript
Click ▶ Run to execute
Ctrl+Enter to run · Tab to indent