Skip to main content
If you already know NumPy in Python, you will feel at home with numpy-ts. This guide covers the key differences so you can migrate existing code or switch between the two with confidence.

Importing

import numpy as np

Creating arrays

a = np.array([1, 2, 3])
b = np.array([[1, 2], [3, 4]], dtype=np.float32)
z = np.zeros((3, 3))
r = np.arange(0, 10, 2)
l = np.linspace(0, 1, 5)
I = np.eye(3)
Shape arguments use arrays in numpy-ts, not separate arguments or tuples. Write np.zeros([3, 3]), not np.zeros(3, 3) or np.zeros((3, 3)).

Arithmetic

c = a + b
d = a * b
e = a ** 2
f = np.sqrt(a)
g = np.dot(a, b)
numpy-ts does not overload JavaScript operators. Use np.add(a, b) or a.add(b) instead of a + b. Method chaining (.add(), .reshape(), etc.) is available on NDArray from the full entry point. See Tree-Shaking & Bundle Size for details on the two entry points.

Indexing and slicing

This is the biggest syntax change. Python uses bracket notation with colons; numpy-ts uses a .slice() method with string arguments.
a = np.arange(12).reshape(3, 4)

a[0, 2]           # Single element
a[0:2, :]         # First 2 rows
a[:, 1:3]         # Columns 1-2
a[::-1, :]        # Reverse rows
a[-1, :]          # Last row
a[1]              # Second row (implicit full slice on remaining dims)

Slicing syntax reference

Pythonnumpy-tsDescription
a[i]a.item(i) (scalar) or a.slice('i', ':') (row)Single index
a[i, j]a.item(i, j)Single element
a[0:5]a.slice('0:5')Range
a[::2]a.slice('::2')Every other element
a[::-1]a.slice('::-1')Reverse
a[0:5, :]a.slice('0:5', ':')Multi-axis slice
a[:, 1:3]a.slice(':', '1:3')Column slice

Reshaping

b = a.reshape(3, 4)        # Separate args
c = a.reshape((3, 4))      # Tuple arg
d = a.T                    # Transpose
e = a.flatten()
f = np.squeeze(a)

Reductions

np.sum(a)
np.sum(a, axis=0)
np.mean(a, axis=1)
np.std(a)
np.var(a)
np.min(a)
np.max(a)
np.argmax(a, axis=0)

Linear algebra

np.linalg.inv(A)
np.linalg.det(A)
np.linalg.eig(A)
np.linalg.svd(A)
np.linalg.norm(v)
np.linalg.solve(A, b)
np.linalg.qr(A)
np.linalg.cholesky(A)
np.linalg.lstsq(A, b)
np.linalg.matrix_rank(A)
The linalg namespace is identical between NumPy and numpy-ts. No changes needed for these calls beyond the import.

Random

np.random.seed(42)
np.random.random((3, 3))
np.random.normal(0, 1, (1000,))
np.random.randint(0, 10, size=(5,))
np.random.choice(arr, size=5, replace=False)
np.random.shuffle(arr)
numpy-ts currently uses different RNGs than NumPy. This means that the generated random numbers will not match NumPy’s output, even with the same seed. Statistical properties (distributions, means, variances) will be the same, but exact sequences will differ.

FFT

spectrum = np.fft.fft(signal)
freqs = np.fft.fftfreq(n, d=1/256)
shifted = np.fft.fftshift(spectrum)

File I/O

arr = np.load('data.npy')
np.save('output.npy', arr)
data = np.load('data.npz')
np.savez('output.npz', x=arr1, y=arr2)
table = np.loadtxt('data.csv', delimiter=',')
np.savetxt('out.csv', arr, delimiter=',')
File I/O is only available from numpy-ts/node. The main numpy-ts entry point exports buffer-based parsers and serializers (parseNpy, serializeNpy) that work in any environment.

Common gotchas

GotchaPython (NumPy)TypeScript (numpy-ts)Notes
Operator overloadinga + b, a * bnp.add(a, b) or a.add(b)JS does not support operator overloading
Shape argumentsreshape(3, 3) or reshape((3, 3))reshape([3, 3])Always use an array, never separate args
Indexinga[0:5, :]a.slice('0:5', ':')String-based slicing
Keyword argumentsaxis=0, keepdims=TruePositional or options objectJS has no keyword args
var is reservednp.var(a)np.variance(a)var is a JS reserved word; np.var is also aliased but may conflict
Transposea.Ta.TSame syntax — .T is a getter property
Array equalitya == b (element-wise)np.equal(a, b) or np.array_equal(a, b)== compares object references in JS
Tuple axesaxis=(0, 2)axis=[0, 2]Use arrays instead of tuples
int64/uint64Regular integersBigInt valuesTypedArray requirement; np.array([1n, 2n, 3n], 'int64')
In-place opsa += bNot supportednumpy-ts operations always return new arrays
dtype specificationdtype=np.float32'float32' (string)Dtypes are string literals in numpy-ts

Supported dtypes

numpy-ts supports 13 data types that map to JavaScript TypedArrays:
CategoryDtypesJS StorageNotes
Floating pointfloat64 (default), float32Float64Array, Float32Array
Signed integerint8, int16, int32, int64Int8ArrayBigInt64Arrayint64 uses BigInt
Unsigned integeruint8, uint16, uint32, uint64Uint8ArrayBigUint64Arrayuint64 uses BigInt
BooleanboolUint8ArrayStored as 0/1
Complexcomplex64, complex128Interleaved Float32Array/Float64ArrayComplex class for elements
When working with int64 or uint64, array elements are BigInt values. Use the n suffix for literals: np.array([1n, 2n, 3n], 'int64').

What about missing NumPy features?

numpy-ts covers 476 of 507 NumPy functions (94%). A few categories have partial coverage:
  • Structured arrays / record dtypes — not supported (JS has no equivalent)
  • String operations (np.char) — not supported (use native JS string methods)
  • np.ma (masked arrays) — not supported yet
  • np.matrix — deprecated in NumPy itself; use 2D NDArray instead
For everything else — math, linear algebra, FFT, random, sorting, sets, polynomials, bitwise operations, I/O — numpy-ts has you covered.

Next steps