Cyforanumera
npm

API reference

Indexing

JavaScript has no a[1:3, ::2] syntax, so indexing uses methods. A slice is a tuple [start, stop, step] in which null means omitted. Basic indices (integers, slices, newaxis, ellipsis) return views; integer-array and boolean-mask indices return copies, as in NumPy.

NameSummary
a.getNumPy a[i, j, ...], with one spec per axis: an integer, a slice tuple, np.newaxis, np.ellipsis, an integer NDArray or a boolean mask.
a.sliceNumPy a[index] from a single list.
a.setNumPy a[index] = value.
np.whereChooses elements from x where condition is true and from y elsewhere, broadcasting all three.
np.nonzeroIndices of the non-zero elements, as one int64 array per dimension.
np.takeTakes elements by index along an axis.
a.taketake with NumPy's mode=: "raise" (default; negative indices count from the end), "wrap" (modulo the axis length) or "clip" (negative indices become 0).
np.takeAlongAxisPick (or write) values using an index array that has the same number of dimensions as arr, matched along axis and broadcast along the other axes, as for the output of argmax(..., keepdims).
np.putSets a.flat[ind] = v in place, repeating v if it is shorter than ind.
np.putmaskWrite values where mask is true, in place.
np.chooseBuilds an array from an index array and a list of choices: out[i] = choices[a[i]][i], with a and every choice broadcast together.
np.compresscompress keeps the slices along axis where the 1-d condition is true (the flattened array if axis is omitted).
np.selectFor each element, takes the value from the first choice whose condition is true, otherwise default (0).
np.piecewiseEvaluates a function defined piece by piece.
np.argwhereargwhere returns the indices of the non-zero elements as an int64 array of shape (N, a.ndim).
np.countNonzeroCounts the non-zero elements (NaN counts as non-zero).
np.ravelMultiIndexConvert between per-dimension indices and flat indices of an array with shape dims.
np.diagonalThe diagonal of the 2-d sub-arrays over axis1 and axis2 (default 0 and 1), as a read-only view like NumPy.
np.traceSum along the diagonal (see diagonal).
a.nonzeroMethod form of np.nonzero: one int64 index array per dimension.

a.get

#
a.get(...index)

NumPy a[i, j, ...], with one spec per axis: an integer, a slice tuple, np.newaxis, np.ellipsis, an integer NDArray or a boolean mask. A full integer index returns a 0-d array; call .item() to get a JS value.

Parameters

...indexIndexSpec[]
One spec per axis.

Returns

NDArray

Example

TypeScript
const b = np.arange(12).reshape(3, 4);
b.get(1);                 // => [4, 5, 6, 7]
b.get(1, -1).item();      // => 7
b.get([0, 2], 1);         // => [1, 5]
b.get(np.ellipsis, 0);    // => [0, 4, 8]
b.get(np.newaxis).shape;  // => [1, 3, 4]
b.get(np.array([2, 0]));  // => [[8, 9, 10, 11], [0, 1, 2, 3]]

a.slice

#
a.slice(index)

NumPy a[index] from a single list. A flat list of numbers/null (length 1–3) is one slice tuple, so a.slice([0, 5]) is a[0:5]. Otherwise it is one spec per axis, so a.slice([[0, 2], [null, null, 2]]) is a[0:2, ::2].

Parameters

indexSliceTuple | IndexSpec[]
Slice tuple or per-axis specs.

Returns

NDArray

Example

TypeScript
const b = np.arange(12).reshape(3, 4);
b.slice([[0, 2], [null, null, 2]]); // => [[0, 2], [4, 6]]
np.arange(5).slice([null, null, -1]); // => [4, 3, 2, 1, 0]
const m = np.array([1, -2, 3, -4]);
m.get(np.array([true, false, true, false])); // => [1, 3]

a.set

#
a.set(index, value)

NumPy a[index] = value. value broadcasts to the selection and is cast to a's dtype. Writes go through to views. Throws ValueError on read-only arrays (for example broadcastTo results).

Parameters

indexIndexSpec | IndexSpec[]
Per-axis specs (like get), or a single spec.
valueNDArray | NestedArray
Values to write.

Returns

void

Example

TypeScript
const c = np.zeros(4);
c.set([[0, 2]], [7, 8]);   // c[0:2] = [7, 8]
c.set(3, 1);               // c[3] = 1
c;                         // => [7, 8, 0, 1]
const d = np.zeros([2, 2]);
d.set([np.ellipsis], 5);   // d[...] = 5
d;                         // => [[5, 5], [5, 5]]

np.where

#
np.where(condition, x, y) / np.where(condition)

Chooses elements from x where condition is true and from y elsewhere, broadcasting all three. With only condition, it is the same as nonzero.

Parameters

conditionNDArray | NestedArray
Boolean selector.
[x], [y]NDArray | NestedArray
Values for true / false (give both or neither).

Returns

NDArray | NDArray[]

Example

TypeScript
np.where([true, false, true], [1, 2, 3], [0, 0, 0]); // => [1, 0, 3]
TypeScript declaration
np.where(condition: NDArray | NestedArray): NDArray[]
np.where(condition: NDArray | NestedArray, x: NDArray | NestedArray, y: NDArray | NestedArray): NDArray

np.nonzero

#
np.nonzero(a)

Indices of the non-zero elements, as one int64 array per dimension.

Parameters

aNDArray | NestedArray
Input array.

Returns

NDArray[]

Example

TypeScript
np.nonzero([0, 3, 0, 4])[0]; // => [1, 3]
np.nonzero([[1, 0], [0, 1]]).map((ix) => ix.toArray()); // => [[0, 1], [0, 1]]
TypeScript declaration
np.nonzero(a: NDArray | NestedArray): NDArray[]

np.take

#
np.take(a, indices, [axis])

Takes elements by index along an axis. Without axis, the array is indexed as if flattened.

Parameters

aNDArray | NestedArray
Source array.
indicesNDArray | NestedArray
Integer indices.
[axis]number | null
Axis to take along. Default: the flattened array.

Returns

NDArray

Example

TypeScript
const a = np.array([[1, 2], [3, 4]]);
np.take(a, [3, 0]);    // => [4, 1]
np.take(a, [1], 1);    // => [[2], [4]]
TypeScript declaration
np.take(a: NDArray | NestedArray, indices: NDArray | NestedArray, axis?: number | TakeOptions | null | undefined, opts?: TakeOptions | undefined): NDArray

a.take

#
np.take(a, indices, [axis], { mode? }) · np.take(a, indices, { axis?, mode? }) · a.take(indices, ...)

take with NumPy's mode=: "raise" (default; negative indices count from the end), "wrap" (modulo the axis length) or "clip" (negative indices become 0). Also available as the method a.take.

Parameters

aArrayLike
An NDArray, nested JS array or scalar.
indicesArrayLike
Integer indices.
[axis]number | null
Axis; default the flattened array.
[options.mode]"raise" | "wrap" | "clip"
Out-of-range indices: raise (default), wrap around, or clip to the valid range.

Returns

NDArray

Example

TypeScript
const a = np.array([[1, 2], [3, 4]]);
np.take(a, [-1, 5], { mode: "wrap" }); // => [4, 2]
a.take([9], 1, { mode: "clip" });      // => [[2], [4]]
TypeScript declaration
a.take(indices: ArrayLike, axis?: number | TakeOptions | null | undefined, opts?: TakeOptions | undefined): NDArray
np.take(a: NDArray | NestedArray, indices: NDArray | NestedArray, axis?: number | TakeOptions | null | undefined, opts?: TakeOptions | undefined): NDArray

np.takeAlongAxis

#
np.takeAlongAxis(arr, indices, axis = -1) · np.putAlongAxis(arr, indices, values, axis)

Pick (or write) values using an index array that has the same number of dimensions as arr, matched along axis and broadcast along the other axes, as for the output of argmax(..., keepdims). axis: null works on the flattened array and needs 1-d indices. putAlongAxis writes in place and returns undefined.

Parameters

arrArrayLike
An NDArray, nested JS array or scalar.
indicesArrayLike
Integer indices with arr.ndim dimensions.
valuesArrayLike
putAlongAxis only: values, broadcast to the selection.
axisnumber | null
Axis to index along.

Returns

NDArray (takeAlongAxis) · void (putAlongAxis)

Example

TypeScript
const a = np.array([[10, 30, 20], [60, 40, 50]]);
np.takeAlongAxis(a, [[1], [0]], 1); // => [[30], [60]]
np.putAlongAxis(a, [[1], [0]], 0, 1);
a; // => [[10, 0, 20], [0, 40, 50]]
TypeScript declaration
np.takeAlongAxis(arr: ArrayLike, indices: ArrayLike, axis?: number | null | undefined): NDArray
np.putAlongAxis(arr: NDArray, indices: ArrayLike, values: ArrayLike, axis: number | null): void

np.put

#
np.put(a, ind, v, { mode? }) · a.put(ind, v, { mode? })

Sets a.flat[ind] = v in place, repeating v if it is shorter than ind. Values are cast to a.dtype. Non-contiguous views are written in flat C order.

Parameters

aNDArray
Target array (must be writeable).
indArrayLike
Flat integer indices.
vArrayLike
Values.
[options.mode]"raise" | "wrap" | "clip"
Out-of-range indices: raise (default), wrap around, or clip to the valid range.

Returns

void

Example

TypeScript
const x = np.zeros(4);
np.put(x, [0, 6], [7, 8], { mode: "wrap" });
x; // => [7, 0, 8, 0]
TypeScript declaration
np.put(a: NDArray, ind: ArrayLike, v: ArrayLike, opts?: PutOptions | undefined): void
a.put(ind: ArrayLike, v: ArrayLike, opts?: PutOptions | undefined): void

np.putmask

#
np.putmask(a, mask, values) · np.place(arr, mask, vals)

Write values where mask is true, in place. putmask uses values[i % n] for flat position i; place uses the masked elements in order, vals[k % n] for the k-th one. An NDArray of values must cast safely to the target dtype; JS values are converted to it.

Parameters

aNDArray
Target array.
maskArrayLike
Boolean mask with a.size elements.
valuesArrayLike
Values to write.

Returns

void

Example

TypeScript
const x = np.array([0, 1, 2, 3, 4]);
np.putmask(x, [false, false, true, true, true], [10, 20]);
x; // => [0, 1, 10, 20, 10]
const y = np.array([0, 1, 2, 3, 4]);
np.place(y, [false, false, true, true, true], [10, 20]);
y; // => [0, 1, 10, 20, 10]
TypeScript declaration
np.putmask(a: NDArray, mask: ArrayLike, values: ArrayLike): void
np.place(arr: NDArray, mask: ArrayLike, vals: ArrayLike): void

np.choose

#
np.choose(a, choices, { mode? }) · a.choose(choices, { mode? })

Builds an array from an index array and a list of choices: out[i] = choices[a[i]][i], with a and every choice broadcast together. The result dtype is the promoted dtype of the choices (JS numbers are weak scalars). With "raise", an out-of-range index raises ValueError.

Parameters

aArrayLike
Integer indices into choices.
choicesArrayLike[] | NDArray
Choice arrays (or an array whose first axis enumerates them).
[options.mode]"raise" | "wrap" | "clip"
Out-of-range indices: raise (default), wrap around, or clip to the valid range.

Returns

NDArray

Example

TypeScript
np.choose([0, 1, 2], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]); // => [1, 5, 9]
np.choose([0, 5], [[1, 2], [3, 4]], { mode: "clip" });      // => [1, 4]
TypeScript declaration
np.choose(a: ArrayLike, choices: NDArray | readonly Operand[], opts?: ChooseOptions | undefined): NDArray
a.choose(choices: NDArray | readonly Operand[], opts?: ChooseOptions | undefined): NDArray

np.compress

#
np.compress(condition, a, [axis]) · a.compress(condition, [axis]) · np.extract(condition, arr)

compress keeps the slices along axis where the 1-d condition is true (the flattened array if axis is omitted). extract flattens both condition and arr and returns the elements where the condition is true.

Parameters

conditionArrayLike
Boolean selector.
aArrayLike
An NDArray, nested JS array or scalar.
[axis]number | null
compress only.

Returns

NDArray

Example

TypeScript
const a = np.array([[1, 2], [3, 4], [5, 6]]);
np.compress([false, true, true], a, 0); // => [[3, 4], [5, 6]]
np.extract([[true, false], [false, true], [true, false]], a); // => [1, 4, 5]
TypeScript declaration
np.compress(condition: ArrayLike, a: ArrayLike, axis?: number | AxisOptions | null | undefined): NDArray
a.compress(condition: ArrayLike, axis?: number | AxisOptions | null | undefined): NDArray
np.extract(condition: ArrayLike, arr: ArrayLike): NDArray

np.select

#
np.select(condlist, choicelist, { default? })

For each element, takes the value from the first choice whose condition is true, otherwise default (0). All arrays broadcast together. Conditions must be boolean arrays.

Parameters

condlistArrayLike[]
Boolean conditions.
choicelistArrayLike[]
One choice per condition.
[options.default]number | ArrayLike
Value where no condition holds.

Returns

NDArray

Example

TypeScript
const x = np.array([0, 1, 2, 3]);
np.select([[true, true, false, false], [false, true, true, false]], [x, np.multiply(x, 10)], { default: -1 }); // => [0, 1, 20, -1]
TypeScript declaration
np.select(condlist: readonly ArrayLike[], choicelist: readonly ArrayLike[], opts?: SelectOptions | undefined): NDArray

np.piecewise

#
np.piecewise(x, condlist, funclist)

Evaluates a function defined piece by piece. Each entry of funclist is a constant or a JS callback that receives the selected elements x[cond] (only when there are any). An extra last entry applies where no condition is true. Elements covered by no piece are 0.

Parameters

xArrayLike
An NDArray, nested JS array or scalar.
condlistArrayLike | ArrayLike[]
One boolean condition or a list of them.
funclist(number | ((x: NDArray) => ArrayLike))[]
Pieces, one per condition (plus an optional otherwise piece).

Returns

NDArray

Example

TypeScript
const x = np.array([-2, -1, 0, 1, 2]);
np.piecewise(x, [[true, true, false, false, false]], [(v) => np.negative(v), 100]); // => [2, 1, 100, 100, 100]
TypeScript declaration
np.piecewise(x: ArrayLike, condlist: ArrayLike | readonly ArrayLike[], funclist: readonly PiecewiseFunc[]): NDArray

np.argwhere

#
np.argwhere(a) · np.flatnonzero(a)

argwhere returns the indices of the non-zero elements as an int64 array of shape (N, a.ndim). flatnonzero returns the indices in the flattened array.

Parameters

aArrayLike
An NDArray, nested JS array or scalar.

Returns

NDArray

Example

TypeScript
np.argwhere([[0, 3], [4, 0]]);   // => [[0, 1], [1, 0]]
np.flatnonzero([[0, 3], [4, 0]]); // => [1, 2]
TypeScript declaration
np.argwhere(a: ArrayLike): NDArray
np.flatnonzero(a: ArrayLike): NDArray

np.countNonzero

#
np.countNonzero(a, { axis?, keepdims? })

Counts the non-zero elements (NaN counts as non-zero). Returns int64; without axis the result is a 0-d array, so call .item() for a number.

Parameters

aArrayLike
An NDArray, nested JS array or scalar.
[options.axis]number | number[] | null
Axes to count over; default all.
[options.keepdims]boolean
Keep reduced axes with length 1.

Returns

NDArray

Example

TypeScript
const a = np.array([[0, 1, 2], [3, 0, 0]]);
np.countNonzero(a).item();          // => 3
np.countNonzero(a, { axis: 0 });    // => [1, 1, 1]
TypeScript declaration
np.countNonzero(a: ArrayLike, opts?: CountNonzeroOptions | undefined): NDArray

np.ravelMultiIndex

#
np.ravelMultiIndex(multiIndex, dims, { mode?, order? }) · np.unravelIndex(indices, shape, { order? })

Convert between per-dimension indices and flat indices of an array with shape dims. mode (one value or one per dimension) handles out-of-range coordinates; order is "C" (default) or "F". unravelIndex returns one int64 array per dimension.

Parameters

multiIndexArrayLike[]
One integer array per dimension (broadcast together).
dimsnumber[]
Array shape.
[options.mode]"raise" | "wrap" | "clip"
Out-of-range indices: raise (default), wrap around, or clip to the valid range.
[options.order]"C" | "F"
Index order.

Returns

NDArray · NDArray[]

Example

TypeScript
np.ravelMultiIndex([[1, 2], [3, 1]], [3, 4]); // => [7, 9]
np.unravelIndex([7, 9], [3, 4]).map((ix) => ix.toArray()); // => [[1, 2], [3, 1]]
np.ravelMultiIndex([1, 2], [3, 4], { order: "F" }).item(); // => 7
TypeScript declaration
np.ravelMultiIndex(multiIndex: readonly ArrayLike[], dims: number | Shape, opts?: RavelMultiIndexOptions | undefined): NDArray
np.unravelIndex(indices: ArrayLike, shape: number | Shape, opts?: { order?: MemoryOrder | undefined; } | undefined): NDArray[]

np.diagonal

#
np.diagonal(a, { offset?, axis1?, axis2? }) · a.diagonal(...)

The diagonal of the 2-d sub-arrays over axis1 and axis2 (default 0 and 1), as a read-only view like NumPy. The diagonal becomes the last axis. offset > 0 is above the main diagonal. A number argument is the offset.

Parameters

aArrayLike
An NDArray, nested JS array or scalar.
[options.offset]number
Diagonal offset. Default 0.
[options.axis1], [options.axis2]number
The two axes. Default 0 and 1.

Returns

NDArray

Example

TypeScript
const m = np.arange(9).reshape(3, 3);
np.diagonal(m);          // => [0, 4, 8]
m.diagonal(1);           // => [1, 5]
m.diagonal().flags.writeable; // => false
TypeScript declaration
np.diagonal(a: ArrayLike, opts?: number | DiagonalOptions | undefined): NDArray
a.diagonal(opts?: number | DiagonalOptions | undefined): NDArray

np.trace

#
np.trace(a, { offset?, axis1?, axis2?, dtype? }) · a.trace(...)

Sum along the diagonal (see diagonal). Uses the sum dtype rules: bool and signed integers give int64, unsigned integers uint64, unless dtype is given. Returns a 0-d array for 2-d input.

Parameters

aArrayLike
An NDArray, nested JS array or scalar.
[options.offset]number
Diagonal offset.
[options.axis1], [options.axis2]number
The two axes.
[options.dtype]DTypeLike
Accumulator/result dtype.

Returns

NDArray

Example

TypeScript
np.trace([[1, 2], [3, 4]]).item(); // => 5
np.trace(np.arange(8).reshape(2, 2, 2), { axis1: 1, axis2: 2 }); // => [3, 11]
TypeScript declaration
np.trace(a: ArrayLike, opts?: number | TraceOptions | undefined): NDArray
a.trace(opts?: number | TraceOptions | undefined): NDArray

a.nonzero

#
a.nonzero()

Method form of np.nonzero: one int64 index array per dimension.

Returns

NDArray[]

Example

TypeScript
np.array([0, 2, 0, 3]).nonzero()[0]; // => [1, 3]
TypeScript declaration
a.nonzero(): NDArray[]