Cyforanumera
npm

API reference

NDArray

Every function returns an NDArray, a handle to data held in native memory. Read the values with toArray(), item() or toTypedArray().

NameSummary
np.attributesRead-only array metadata.
a.toArrayCopies the data into nested JS arrays.
a.itemReturns a single element as a JS number or boolean.
a.toTypedArrayCopies the data into a TypedArray of the matching element type (BigInt64Array for int64).
a.reshapeSame data with a new shape.
a.TTransposed view with no copy.
a.astypeCopy converted to another dtype.
a.copyDeep, C-contiguous copy of the array.
a.toStringNumPy-style representation, also used by console.log.
a.fillSets every element to value, cast to the array's dtype like np.array(value, {dtype}) (floats truncate for integer dtypes; out-of-range integers and NaN raise ValueError).
a.tolistNested JS arrays of the elements, the same as toArray() (NumPy name).
a.tobytesA new Uint8Array with the raw bytes of the elements, in "C" (default and "K"), "F" or "A" order.
a.viewA new view of the same memory, optionally reinterpreted as another dtype.
a.byteswapReverses the bytes of every element (each component for complex).
a.setflagsSets the writeable flag.
a.baseThe array that owns the memory this array views, or null if it owns its data (NumPy base, same object identity).
a.mTView with the last two axes swapped (matrix transpose of a stack).
a.flatA FlatIter: a 1-D, C-order view of the elements.
a.astypeConverted copy.
a.dotSame as np.dot(a, b).

np.attributes

#
a.shape · a.ndim · a.size · a.dtype · a.strides · a.itemSize · a.nbytes · a.flags

Read-only array metadata. strides are in bytes. flags holds cContiguous, fContiguous, writeable and ownData.

Returns

number[] | number | DType | ArrayFlags

Example

TypeScript
const a = np.zeros([2, 3], { dtype: "float32" });
a.shape;    // => [2, 3]
a.ndim;     // => 2
a.size;     // => 6
a.itemSize; // => 4
a.nbytes;   // => 24
a.strides;  // => [12, 4]
TypeScript declaration
a.shape: number[]
a.ndim: number
a.size: number
a.dtype: DType
a.strides: number[]
a.itemSize: number
a.nbytes: number
a.flags: ArrayFlags

a.toArray

#
a.toArray()

Copies the data into nested JS arrays. int64/uint64 values beyond 2^53 lose precision; use toTypedArray() for those. Complex arrays throw NotImplementedError; use toTypedArray() to read them.

Returns

NestedArray

Example

TypeScript
np.arange(4).reshape(2, 2).toArray(); // => [[0, 1], [2, 3]]

a.item

#
a.item([...index])

Returns a single element as a JS number or boolean. With no index, the array must have exactly one element.

Parameters

[...index]number[]
One integer per axis (negative counts from the end).

Returns

number | boolean

Example

TypeScript
const a = np.array([[1, 2], [3, 4]]);
a.item(1, 0);      // => 3
np.sum(a).item();  // => 10
TypeScript declaration
a.item(...index: number[]): number | boolean | Complex

a.toTypedArray

#
a.toTypedArray()

Copies the data into a TypedArray of the matching element type (BigInt64Array for int64). Complex arrays come out interleaved as [re, im, re, im, ...].

Returns

ArrayBufferView

Example

TypeScript
const t = np.array([1, 2, 3], { dtype: "float32" }).toTypedArray();
t instanceof Float32Array; // => true

a.reshape

#
a.reshape(shape) / a.reshape(...dims)

Same data with a new shape. Returns a view when the layout allows it. One dimension may be -1 and is then inferred.

Parameters

shapenumber[] | ...number
New dimensions.

Returns

NDArray

Example

TypeScript
np.arange(6).reshape(2, 3); // => [[0, 1, 2], [3, 4, 5]]
np.arange(6).reshape([-1, 2]).shape; // => [3, 2]
TypeScript declaration
a.reshape(shape: number | Shape, ...rest: (number | OrderOptions)[]): NDArray

a.T

#
a.T · a.transpose([...axes])

Transposed view with no copy. transpose() reverses the axes, or permutes them in the order given.

Returns

NDArray

Example

TypeScript
const a = np.array([[1, 2, 3], [4, 5, 6]]);
a.T; // => [[1, 4], [2, 5], [3, 6]]
np.zeros([2, 3, 4]).transpose(1, 0, 2).shape; // => [3, 2, 4]
TypeScript declaration
a.T: NDArray
a.transpose(...axes: number[] | [readonly number[]]): NDArray

a.astype

#
a.astype(dtype)

Copy converted to another dtype. Float → int truncates toward zero, as in NumPy.

Parameters

dtypeDTypeLike
Target dtype.

Returns

NDArray

Example

TypeScript
np.array([1.7, -2.7]).astype("int32"); // => [1, -2]
TypeScript declaration
a.astype(dt: DTypeLike, opts?: AstypeOptions | undefined): NDArray

a.copy

#
a.copy()

Deep, C-contiguous copy of the array. ravel() flattens to a view when possible; flatten() always copies.

Returns

NDArray

Example

TypeScript
const a = np.array([[1, 2], [3, 4]]);
const b = a.copy();
np.mayShareMemory(a, b); // => false
a.T.flatten();           // => [1, 3, 2, 4]
TypeScript declaration
a.copy(opts?: OrderOptions | undefined): NDArray

a.toString

#
String(a)

NumPy-style representation, also used by console.log.

Returns

string

Example

TypeScript
String(np.array([1, 2])); // => "array([1, 2])"

a.fill

#
a.fill(value)

Sets every element to value, cast to the array's dtype like np.array(value, {dtype}) (floats truncate for integer dtypes; out-of-range integers and NaN raise ValueError).

Parameters

valuenumber | boolean | bigint | Complex | NDArray
A scalar or a size-1 array.

Returns

void

Example

TypeScript
const a = np.zeros([2], { dtype: "int32" });
a.fill(7.9);
a.toArray(); // => [7, 7]
TypeScript declaration
a.fill(value: number | bigint | boolean | NDArray | ComplexLike): void

a.tolist

#
a.tolist()

Nested JS arrays of the elements, the same as toArray() (NumPy name).

Returns

NestedArray

Example

TypeScript
np.array([[1, 2], [3, 4]]).tolist(); // => [[1, 2], [3, 4]]
TypeScript declaration
a.tolist(): NestedArray

a.tobytes

#
a.tobytes({ order })

A new Uint8Array with the raw bytes of the elements, in "C" (default and "K"), "F" or "A" order.

Returns

Uint8Array

Example

TypeScript
const a = np.array([[0, 1], [2, 3]], { dtype: "uint8" });
Array.from(a.tobytes());                 // => [0, 1, 2, 3]
Array.from(a.tobytes({ order: "F" }));   // => [0, 2, 1, 3]
TypeScript declaration
a.tobytes(opts?: OrderOptions | undefined): Uint8Array<ArrayBufferLike>

a.view

#
a.view([dtype])

A new view of the same memory, optionally reinterpreted as another dtype. With a different item size the last axis is rescaled; it must be contiguous and its byte size divisible by the new item size (otherwise ValueError, as NumPy).

Returns

NDArray

Example

TypeScript
const a = np.array([1, 2], { dtype: "int32" });
a.view("uint8").toArray(); // => [1, 0, 0, 0, 2, 0, 0, 0]
a.view().base === a;       // => true
TypeScript declaration
a.view(dt?: DTypeLike | undefined): NDArray

a.byteswap

#
a.byteswap({ inplace = false })

Reverses the bytes of every element (each component for complex). Returns a copy, or swaps in place and returns a.

Returns

NDArray

Example

TypeScript
np.array([1, 2], { dtype: "int16" }).byteswap(); // => [256, 512]
TypeScript declaration
a.byteswap(opts?: { inplace?: boolean | undefined; } | undefined): NDArray

a.setflags

#
a.setflags({ write })

Sets the writeable flag. write: true raises ValueError when the array that owns the memory is read-only. align/uic are not supported.

Returns

void

Example

TypeScript
const a = np.array([1, 2]);
a.setflags({ write: false });
a.flags.writeable; // => false
TypeScript declaration
a.setflags(opts?: { write?: boolean | null | undefined; align?: boolean | null | undefined; uic?: boolean | null | undefined; } | undefined): void

a.base

#
a.base

The array that owns the memory this array views, or null if it owns its data (NumPy base, same object identity).

Returns

NDArray | null

Example

TypeScript
const a = np.array([1, 2, 3]);
a.base;               // => null
a.get([1, 3]).base === a; // => true
TypeScript declaration
a.base: NDArray | null

a.mT

#
a.mT

View with the last two axes swapped (matrix transpose of a stack). Arrays with fewer than 2 dimensions raise ValueError.

Returns

NDArray

Example

TypeScript
np.zeros([5, 2, 3]).mT.shape; // => [5, 3, 2]
TypeScript declaration
a.mT: NDArray

a.flat

#
a.flat

A FlatIter: a 1-D, C-order view of the elements. flat.get(i) takes an integer (returns a JS scalar), a slice tuple, an integer index array or a boolean mask (returns a new array); flat.set(i, value) repeats value cyclically over the selection; a.flat = v assigns to every element. It is also iterable, and has base, index, coords, length and copy().

Returns

FlatIter

Example

TypeScript
const a = np.array([[1, 2], [3, 4]]);
a.T.flat.get(1);      // => 3
a.flat.get([1, 4]);   // => [2, 3, 4]
a.flat.set(np.array([0, 3]), [9, 8]);
a.toArray();          // => [[9, 2], [3, 8]]
[...a.T.flat];        // => [9, 3, 2, 8]
TypeScript declaration
a.flat: FlatIter

a.astype options

#
a.astype(dtype, { order, copy, casting })

Converted copy. casting (default "unsafe") is checked with canCast first and a disallowed cast raises DTypeError; copy: false returns a itself when nothing would change; order defaults to "K".

Returns

NDArray

Example

TypeScript
np.array([1.7, -2.2]).astype("int32"); // => [1, -2]
const f = np.array([1.5]);
f.astype("float64", { copy: false }) === f; // => true
TypeScript declaration
a.astype(dt: DTypeLike, opts?: AstypeOptions | undefined): NDArray

a.dot

#
a.dot(b)

Same as np.dot(a, b).

Parameters

bArrayLike
An NDArray or nested JS array.

Returns

NDArray

Example

TypeScript
np.array([[1, 2], [3, 4]]).dot([1, 1]); // => [3, 7]
TypeScript declaration
a.dot(b: ArrayLike): NDArray