Catalogue / numpy-array-workflows
numpy-array-workflows
Older skill: source not recordedSignedApplies NumPy array creation, indexing, broadcasting, statistics, linear algebra, random simulation, transforms, and file formats with shape and memory checks. Use for dense numerical computing. Do not use as a substitute for symbolic math, sparse storage, dataframe semantics, or deep-learning frame…--- name: numpy-array-workflows description: >- Applies NumPy array creation, indexing, broadcasting, statistics, linear algebra, random simulation, transforms, and file formats with shape and memory checks. Use for dense numerical computing. Do not use as a substitute for symbolic math, sparse storage, dataframe semantics, or deep-learning frameworks. ---
Establish shape, precision, and ownership
Use an independently installed verified NumPy and inspect np.__version__; examples are grounded in the documented 1.26-era API but must be checked against the installed release. Import numpy as np rather than wildcard names. Use pandas for labeled complex tables, SymPy for symbolic math, scipy.sparse for sparse matrices, built-in strings for text, and appropriate training frameworks for deep learning.
Before computing, record for every array:
shape,ndim,dtype, and physical units- missing-value policy (sentinel vs
nan) and what each axis means - the memory budget — big broadcasts allocate more than the inputs
Writing or replacing files, installing packages, or mutating arrays the caller supplied needs the user's explicit go-ahead. Fresh in-memory examples have no external effects; fetching or installing remote code is never part of this workflow.
Select the operation with its shape contract
| Need | APIs and checks | | --- | --- | | Build arrays | array from list/tuple/nested/complex data with explicit dtype; zeros, ones, full, eye, diag. empty is uninitialized and must be fully filled before reading. | | Sample a range | arange for a step (floating endpoints can be imprecise), linspace for a count/endpoints, logspace for exponent spacing, geomspace for geometric spacing. | | Index/slice | Positive/negative indices, start/stop/step, reverse, row/column/subarray slices. Basic slices usually share storage; integer/boolean advanced indexing produces copies. | | Select conditions | Parenthesized comparisons with &, |, and ~; where locates matches. Fancy row/column vectors select paired coordinates; ix_ selects their Cartesian grid. | | Elementwise math | Addition/subtraction/multiplication/division/power/floor division/remainder; sin, cos, tan, arcsin, exp, log, log10, sqrt, abs, round, floor, ceil. Respect domains and ties-to-even rounding. | | Reduce | sum, mean, std, var, min, max, argmin, argmax, median, percentile, histogram, corrcoef; specify axis/keepdims and desired ddof. | | Reshape/combine | reshape with compatible element count and one inferred -1; transpose, flatten copy, ravel view when possible; vstack, hstack, column_stack, concatenate, and equal-size split. | | Missing/equality | isnan, nanmean, nanstd, nansum, or deliberate mask removal; distinguish all-missing behavior. == is valid elementwise, while scalar decisions need array_equal, all, or tolerance-based allclose. |
Broadcast dimensions compare from the right: each pair must match or one must be 1. Use newaxis for row/column expansion; broadcast_to often returns a readonly shared view. Guard zero-variance standardization and bound large broadcast intermediates. Integer assignments truncate fractional values; examine promotion, overflow, and casting instead of mixing dtypes blindly.
import numpy as np
def standardize_columns(values):
data = np.asarray(values, dtype=np.float64)
if data.ndim != 2 or data.shape[0] == 0:
raise ValueError('need a nonempty sample-by-feature matrix')
center = np.mean(data, axis=0, keepdims=True)
scale = np.std(data, axis=0, keepdims=True)
safe = np.where(scale == 0, 1.0, scale)
return (data - center) / safe
points = np.array([[0., 0.], [0., 4.], [3., 0.]])
difference = points[:, None, :] - points[None, :, :]
distances = np.sqrt(np.sum(difference ** 2, axis=-1))
nearest_distances = distances.copy()
np.fill_diagonal(nearest_distances, np.inf)
nearest = np.argmin(nearest_distances, axis=1)
windows = np.lib.stride_tricks.sliding_window_view(np.arange(9.), 3)
window_means, window_stds = windows.mean(axis=-1), windows.std(axis=-1)Distance matrices cost quadratic memory; chunk large inputs and define behavior for fewer than two points. Prefer validated sliding_window_view to hand-built unsafe as_strided; windows overlap and should not be mutated. Validate window length and dimensionality.
Solve and verify numerical systems
Use @ for matrix multiplication; * remains elementwise and dot has different high-dimensional behavior. Inspect transpose, trace, and linalg.matrix_power as needed. Prefer linalg.solve over forming an inverse for a system; inv and det remain available when mathematically required. Examine conditioning and singular failures.
matrix = np.array([[5., 1.], [1., 3.]]) target = np.array([11., 7.]) solution = np.linalg.solve(matrix, target) assert np.allclose(matrix @ solution, target) values, vectors = np.linalg.eigh(matrix) # Hermitian/symmetric input assert np.allclose(matrix @ vectors, vectors * values) u, singular, vh = np.linalg.svd(matrix, full_matrices=False) assert np.allclose((u * singular) @ vh, matrix)
Use eig for a general square matrix and verify each eigenvector relation; use the appropriate symmetric/Hermitian solver when applicable. SVD handles rectangular matrices too. linalg.norm supports Frobenius/default matrix norm, maximum-column-sum order 1, maximum-row-sum infinity norm, and spectral order 2. Choose tolerances from scale and required precision, not copied constants.
Simulate with an explicit generator
Prefer random.default_rng(seed) and pass the generator to helpers. Legacy seed, rand, randn, and randint affect shared state; retain them only for deliberate compatibility. Generator methods include random, integers, normal, uniform, exponential, binomial, poisson, beta, chisquare, weighted/unweighted choice, and in-place shuffle. Validate distribution parameters, replacement limits, and probability sums; reproducibility depends on generator/version and call order.
def quarter_circle_estimate(samples, seed=73):
if samples <= 0:
raise ValueError('positive sample count required')
rng = np.random.default_rng(seed)
inside = 0
remaining = samples
while remaining:
count = min(remaining, 4096)
xy = rng.random((count, 2))
inside += np.count_nonzero(np.sum(xy ** 2, axis=1) <= 1)
remaining -= count
return 4 * inside / samples
rng = np.random.default_rng(19)
x = np.linspace(-2, 2, 31)
y = 3 * x ** 2 - x + 4 + rng.normal(0, 0.2, x.shape)
coefficients = np.polyfit(x, y, deg=2)
predicted = np.polyval(coefficients, x)
rmse = np.sqrt(np.mean((y - predicted) ** 2))
polynomial = np.poly1d(coefficients)Monte Carlo error varies with sample size; the batching limit above is a memory choice, not an accuracy promise. Polynomial fitting needs degree/data/conditioning checks, residual review, and held-out evaluation if predicting. Descriptive analysis can report mean/median/std/variance, quartiles/IQR, histogram bins, and correlation without implying causation.
Transform signals, images, and structured records
For basic Fourier analysis, inspect installed np.fft APIs, sample spacing, transformed axis, frequency bins, normalization, and inverse reconstruction. Use complex or real-input transforms as appropriate and check aliasing/windowing assumptions; an FFT alone does not establish signal meaning.
For numeric image arrays use rot90, flipud, fliplr, or transpose with clear channel-axis handling. Map a nonconstant grayscale range to 0–255 and cast to uint8; define a constant-image result to avoid division by zero and avoid silently discarding NaNs. This covers array transformations, not a full image editor.
Structured dtypes combine named fields such as a Unicode label, integer count, and float measurement. Access by field and sort(..., order='field'); define string width to avoid silent truncation. Complex tabular workflows may suit a dataframe better.
Preserve data safely and measure performance
After explicit output approval, savetxt supports delimiter/format; loadtxt supports delimiter, skiprows, and usecols. .npy preserves one array; savez preserves named arrays without compression and savez_compressed compresses them. Load untrusted numeric files with allow_pickle=False, constrain size, and close NPZ handles. Use a reviewed output path and refuse unintended overwrites.
Inspect flags, nbytes, and itemsize; convert with ascontiguousarray or asfortranarray when measured workloads need C/Fortran layout. .base is only a clue: use shares_memory/may_share_memory where appropriate. A small view can retain a large parent allocation; copy the small result when independence/lifetime requires it.
Performance habits:
- Preallocate; never grow an array with repeated
np.appendin a loop. - Benchmark representative sizes with a monotonic timer (
time.perf_counter), correctness first. np.vectorize— decorator or constructor — is a convenience Python loop, not a compiled ufunc.- Compound expressions create temporaries; NumPy does not fuse them automatically. Use in-place or
out=operations (with casting/alias checks), or a reviewed numexpr install when justified. - Plain loops stay appropriate for irregular work — vectorizing them may not pay.
Never
- Write files, modify caller data/code/settings, install, or start external processes without explicit confirmation.
- Load untrusted pickles, read uninitialized arrays, or use unchecked stride tricks.
- Treat equality arrays as scalar booleans, ignore dtype overflow/NaNs/shape, or assume every reshape is a view.
- Claim vectorize is compiled acceleration, expressions always fuse, or simulation/fit results guarantee accuracy.
- Write over an existing data file, or grow arrays by repeated append inside a loop.
- Fit or extrapolate a polynomial without checking conditioning, residuals, and held-out error.
- Hand
as_stridedan unvalidated shape/stride pair, or mutate a sliding-window or broadcast view.
| File | Size | SHA-256 |
|---|---|---|
| SKILL.md | 10.3 kB | 9d36cc31e3ea |
| examples.json | 1.7 kB | 03c0e86c2564 |
Published verbatim from the pinned commit. Nothing is rewritten.
| Version | Pinned commit | Signed | |
|---|---|---|---|
| 1.0.1 Current | Not recorded | 6 Oct 2026 | |
| 1.0.0 | Not recorded | 3 Oct 2026 |
Locking a skill to one version needs Pro.