API reference
Utilities
| Name | Summary |
|---|---|
np.mayShareMemory | true if the two arrays may share memory, i.e. |
np.copy | A copy of a. |
np.ascontiguousarray | a as a C-contiguous array with at least one dimension; no copy when it already is. |
np.asfortranarray | a as an F-contiguous (column-major) array with at least one dimension; no copy when it already is. |
np.memoryStats | Count and total size of the native buffers currently alive. |
np.lib.stride_tricks.asStrided | View of the same memory with arbitrary shape and byte strides. |
np.ndindex | Generator of every index of shape (dimensions as arguments or one array) in C order. |
np.ndenumerate | Generator of [index, value] pairs in C order; values are JS scalars. |
np.nditer | Read-only multi-dimensional iterator (NDIter). |
np.arrayRepr | NumPy array_repr: array(...) text with shape=/dtype= added when they cannot be inferred. |
np.arrayStr | NumPy array_str (Python str(a)): elements separated by spaces; a 0-d array prints like a NumPy scalar. |
np.array2string | NumPy array2string. |
np.formatFloatPositional | NumPy format_float_positional (Dragon4). |
np.formatFloatScientific | NumPy format_float_scientific (Dragon4), with the same argument rules as formatFloatPositional. |
np.setPrintoptions | NumPy set_printoptions: module-wide print options. |
np.getPrintoptions | NumPy get_printoptions: a copy of the current print options (camelCase keys). |
np.printoptions | NumPy's printoptions context manager as a callback: opts apply while fn() runs and are restored afterwards, also if it throws. |
np.baseRepr | String of an integer in base (2 to 36, default 2), with padding zeros added on the left. |
np.binaryRepr | Binary string of an integer. |
np.pi | Mathematical constant π ≈ 3.14159… |
np.e | Euler's number, the base of natural logarithms, ≈ 2.71828… |
np.inf | IEEE 754 positive infinity. |
np.nan | IEEE 754 not-a-number. |
np.euler_gamma | Euler–Mascheroni constant γ ≈ 0.5772156649… |
np.True_ | Python True (JS true). |
np.False_ | Python False (JS false). |
np.PINF | Positive infinity (alias of np.inf). |
np.NINF | Negative infinity. |
np.PZERO | Positive zero. |
np.NZERO | Negative zero. |
np.vectorize | Wraps a JS callback so it is applied element-wise over its inputs, which are broadcast to a common shape. |
np.shares_memory | Returns true if arrays a and b share any underlying memory. |
np.cumsum | Cumulative sum of array elements along the given axis. |
np.cumprod | Cumulative product of array elements along the given axis. |
np.nancumsum | Like cumsum/cumprod but NaN values are treated as 0 / 1 respectively (i.e. |
np.busdaycalendar | A business-day calendar combining a weekmask (which weekdays are business days) and optional holidays. |
np.is_busday | Return true for each date that is a business day (not a weekend and not a holiday). |
np.busday_count | Count the number of business days in [begindates, enddates). |
np.busday_offset | Shift dates by offsets business days. |
np.sharesMemory | Return true if a and b share the same underlying memory buffer (NumPy np.shares_memory). |
np.mayShareMemory
#np.mayShareMemory(a, b)
true if the two arrays may share memory, i.e. one is a view of the other or both view the same buffer.
Parameters
a, bNDArray- Arrays to compare.
Returns
boolean
Example
const a = np.arange(6);
np.mayShareMemory(a, a.reshape(2, 3)); // => true
np.mayShareMemory(a, a.copy()); // => falseTypeScript declaration
np.mayShareMemory(a: NDArray, b: NDArray): booleannp.copy
#np.copy(a, { order? })
A copy of a. order is "K" (default, keep the layout), "A", "C" or "F".
Parameters
aArrayLike- An
NDArray, nested JS array or scalar. orderstring- Memory order of the copy.
Returns
NDArray
Example
np.copy(np.ones([2, 3], { order: "F" })).strides; // => [8, 16]TypeScript declaration
np.copy(a: NDArray | NestedArray, options?: { order?: MemoryOrder | null | undefined; } | undefined): NDArraynp.ascontiguousarray
#np.ascontiguousarray(a, { dtype? })
a as a C-contiguous array with at least one dimension; no copy when it already is.
Parameters
aArrayLike- An
NDArray, nested JS array or scalar.
Returns
NDArray
Example
np.ascontiguousarray(np.arange(6).reshape(2, 3).T).strides; // => [16, 8]TypeScript declaration
np.ascontiguousarray(a: NDArray | NestedArray, options?: ArrayOptions | undefined): NDArraynp.asfortranarray
#np.asfortranarray(a, { dtype? })
a as an F-contiguous (column-major) array with at least one dimension; no copy when it already is.
Parameters
aArrayLike- An
NDArray, nested JS array or scalar.
Returns
NDArray
Example
np.asfortranarray(np.arange(6).reshape(2, 3)).strides; // => [8, 16]TypeScript declaration
np.asfortranarray(a: NDArray | NestedArray, options?: ArrayOptions | undefined): NDArraynp.memoryStats
#np.memoryStats()
Count and total size of the native buffers currently alive. Native memory is freed when the JS objects are garbage-collected.
Returns
{ buffers: number, bytes: number }
Example
const s = np.memoryStats();
typeof s.bytes; // => "number"np.lib.stride_tricks.asStrided
#np.lib.stride_tricks.asStrided(a, [shape], [strides])
View of the same memory with arbitrary shape and byte strides. It is unchecked, as in NumPy: wrong strides can read outside the buffer's logical data.
Parameters
aNDArray- Base array.
[shape]number[]- View shape.
[strides]number[]- Strides in bytes.
Returns
NDArray
Example
const a = np.arange(0, 5, 1, { dtype: "int32" });
np.lib.stride_tricks.asStrided(a, [3, 3], [4, 4]); // => [[0, 1, 2], [1, 2, 3], [2, 3, 4]]np.ndindex
#np.ndindex(...shape)
Generator of every index of shape (dimensions as arguments or one array) in C order. ndindex() yields [] once.
Returns
Generator<number[]>
Example
[...np.ndindex(2, 2)]; // => [[0, 0], [0, 1], [1, 0], [1, 1]]TypeScript declaration
np.ndindex(...shape: (number | readonly number[])[]): Generator<number[], any, any>np.ndenumerate
#np.ndenumerate(a)
Generator of [index, value] pairs in C order; values are JS scalars.
Returns
Generator<[number[], number | boolean | Complex]>
Example
[...np.ndenumerate(np.array([[1, 2], [3, 4]]))]; // => [[[0, 0], 1], [[0, 1], 2], [[1, 0], 3], [[1, 1], 4]]TypeScript declaration
np.ndenumerate(a: Operand): Generator<[number[], ScalarValue], any, any>np.nditer
#np.nditer(op | ops, { flags, order = "K", opFlags })
Read-only multi-dimensional iterator (NDIter). Each step yields a 0-d read-only view (an array of views for several operands, which broadcast together). "K" walks memory order. Flags: multi_index, c_index, f_index, zerosize_ok; members multiIndex, index, iterindex, itersize, shape, ndim, nop, operands, value, finished, iternext(), reset(). Buffering, external_loop and writable operands raise NotImplementedError.
Returns
NDIter
Example
const out = [];
for (const x of np.nditer(np.array([[1, 2], [3, 4]]).T)) out.push(x.item());
out; // => [1, 2, 3, 4]
const it = np.nditer([np.array([[1], [2]]), np.array([10, 20])]);
[...it].map(([x, y]) => x.item() + y.item()); // => [11, 21, 12, 22]np.arrayRepr
#np.arrayRepr(a, { maxLineWidth?, precision?, suppressSmall? })
NumPy array_repr: array(...) text with shape=/dtype= added when they cannot be inferred. Float digits come from a C++ port of NumPy's Dragon4 (shortest unique digits per dtype). String(a) / a.toString() return the same text.
Returns
string
Example
np.arrayRepr(np.array([1, 2])); // => "array([1, 2])"
np.arrayRepr(np.array([1.5, -2, NaN])); // => "array([ 1.5, -2. , nan])"
np.arrayRepr(np.array([-1, 10], { dtype: "int8" })); // => "array([-1, 10], dtype=int8)"TypeScript declaration
np.arrayRepr(a: AnyArray, opts?: ArrayReprOptions | undefined): stringnp.arrayStr
#np.arrayStr(a, { maxLineWidth?, precision?, suppressSmall? })
NumPy array_str (Python str(a)): elements separated by spaces; a 0-d array prints like a NumPy scalar.
Returns
string
Example
np.arrayStr(np.array([1, 2, 3])); // => "[1 2 3]"
np.arrayStr(np.array(1e16)); // => "1e+16"TypeScript declaration
np.arrayStr(a: AnyArray, opts?: ArrayReprOptions | undefined): stringnp.array2string
#np.array2string(a, { maxLineWidth?, precision?, suppressSmall?, separator?, prefix?, suffix?, formatter?, threshold?, edgeitems?, sign?, floatmode?, legacy? })
NumPy array2string. formatter maps NumPy formatter names (all, bool, int, float, complexfloat, int_kind, float_kind, complex_kind) to JS callbacks that get each element and return a string. Only legacy: false is supported (others raise NotImplementedError).
Returns
string
Example
np.array2string(np.array([1, 2, 3]), { separator: "," }); // => "[1,2,3]"
np.array2string(np.array([1.123, 2]), { floatmode: "fixed", precision: 2 }); // => "[1.12 2.00]"TypeScript declaration
np.array2string(a: AnyArray, opts?: Array2StringOptions | undefined): stringnp.formatFloatPositional
#np.formatFloatPositional(x, { precision?, unique?, fractional?, trim?, sign?, padLeft?, padRight?, minDigits? })
NumPy format_float_positional (Dragon4). x is a JS number (float64) or a size-1 NDArray, formatted in its own float dtype (ints/bool as float64; complex raises DTypeError).
Returns
string
Example
np.formatFloatPositional(1); // => "1."
np.formatFloatPositional(0.3, { minDigits: 20 }); // => "0.29999999999999998890"
np.formatFloatPositional(np.array(0.1, { dtype: "float32" }), { unique: false, precision: 10 }); // => "0.1000000015"TypeScript declaration
np.formatFloatPositional(x: number | boolean | NDArray, opts?: FormatFloatPositionalOptions | undefined): stringnp.formatFloatScientific
#np.formatFloatScientific(x, { precision?, unique?, trim?, sign?, padLeft?, expDigits?, minDigits? })
NumPy format_float_scientific (Dragon4), with the same argument rules as formatFloatPositional.
Returns
string
Example
np.formatFloatScientific(123.456, { precision: 2 }); // => "1.23e+02"
np.formatFloatScientific(1e100, { expDigits: 4 }); // => "1.e+0100"TypeScript declaration
np.formatFloatScientific(x: number | boolean | NDArray, opts?: FormatFloatScientificOptions | undefined): stringnp.setPrintoptions
#np.setPrintoptions({ precision?, threshold?, edgeitems?, linewidth?, suppress?, nanstr?, infstr?, sign?, floatmode?, formatter?, legacy?, overrideRepr? })
NumPy set_printoptions: module-wide print options. Omitted options stay unchanged, except formatter and overrideRepr, which reset on every call (like NumPy).
Returns
void
Example
np.setPrintoptions({ precision: 2 });
String(np.array([1 / 3])); // => "array([0.33])"
np.setPrintoptions({ precision: 8 });TypeScript declaration
np.setPrintoptions(opts?: PrintOptionsInput | undefined): voidnp.getPrintoptions
#np.getPrintoptions()
NumPy get_printoptions: a copy of the current print options (camelCase keys).
Returns
PrintOptions
Example
np.getPrintoptions().threshold; // => 1000TypeScript declaration
np.getPrintoptions(): PrintOptionsnp.printoptions
#np.printoptions(opts, fn)
NumPy's printoptions context manager as a callback: opts apply while fn() runs and are restored afterwards, also if it throws. Returns fn's result.
Returns
T
Example
np.printoptions({ precision: 2 }, () => String(np.array([2 / 3]))); // => "array([0.67])"TypeScript declaration
np.printoptions<T>(opts: PrintOptionsInput, fn: () => T): Tnp.baseRepr
#np.baseRepr(number, [base], [padding])
String of an integer in base (2 to 36, default 2), with padding zeros added on the left. Negative numbers get a minus sign. Accepts number, bigint or a 0-d integer array.
Parameters
numbernumber | bigint | NDArray- Integer to convert.
[base]number- Base, 2 to 36 (default 2).
[padding]number- Zeros to prepend (default 0).
Returns
string
Example
np.baseRepr(255, 16); // => "FF"
np.baseRepr(-7, 2, 3); // => "-000111"TypeScript declaration
np.baseRepr(number: IntegerLike, base?: number | undefined, padding?: number | undefined): stringnp.binaryRepr
#np.binaryRepr(num, [options])
Binary string of an integer. Without width, negative numbers get a minus sign; with width, they are written in two's complement. A width that is too small raises ValueError.
Parameters
numnumber | bigint | NDArray- Integer to convert.
[options.width]number- Output length (zero-padded, or two's complement for negatives).
Returns
string
Example
np.binaryRepr(5); // => "101"
np.binaryRepr(-5); // => "-101"
np.binaryRepr(-5, { width: 8 }); // => "11111011"TypeScript declaration
np.binaryRepr(num: IntegerLike, options?: BinaryReprOptions | undefined): stringnp.pi
#np.pi
Mathematical constant π ≈ 3.14159…
Returns
number
Example
np.pi; // => 3.141592653589793TypeScript declaration
np.pi: numbernp.e
#np.e
Euler's number, the base of natural logarithms, ≈ 2.71828…
Returns
number
Example
np.e; // => 2.718281828459045TypeScript declaration
np.e: numbernp.inf
#np.inf
IEEE 754 positive infinity. Aliases: np.PINF, np.Inf, np.Infinity.
Returns
number
Example
np.inf > 1e308; // => trueTypeScript declaration
np.inf: numbernp.nan
#np.nan
IEEE 754 not-a-number. Alias: np.NaN.
Returns
number
Example
np.nan !== np.nan; // => trueTypeScript declaration
np.nan: numbernp.euler_gamma
#np.euler_gamma
Euler–Mascheroni constant γ ≈ 0.5772156649…
Returns
number
Example
Math.abs(np.euler_gamma - 0.5772156649015329) < 1e-15; // => trueTypeScript declaration
np.euler_gamma: numbernp.True_
#np.True_
Python True (JS true). Provided for NumPy API parity.
Returns
boolean
Example
np.True_ === true; // => trueTypeScript declaration
np.True_: truenp.False_
#np.False_
Python False (JS false). Provided for NumPy API parity.
Returns
boolean
Example
np.False_ === false; // => trueTypeScript declaration
np.False_: falsenp.PINF
#np.PINF
Positive infinity (alias of np.inf).
Returns
number
Example
np.PINF === Infinity; // => truenp.NINF
#np.NINF
Negative infinity.
Returns
number
Example
np.NINF === -Infinity; // => truenp.PZERO
#np.PZERO
Positive zero.
Returns
number
Example
1 / np.PZERO === Infinity; // => truenp.NZERO
#np.NZERO
Negative zero.
Returns
number
Example
1 / np.NZERO === -Infinity; // => truenp.vectorize
#np.vectorize(fn, [options])
Wraps a JS callback so it is applied element-wise over its inputs, which are broadcast to a common shape. Returns a callable with a pyfunc property. otypes[0] forces the output dtype; otherwise it is inferred from the first call. signature must be null (scalar-in / scalar-out only).
Parameters
fn(...args: unknown[]) => unknown- The scalar function to apply element-wise.
[options.otypes]DTypeLike[]- Output dtype(s); only the first element is used.
[options.signature]null- Must be
nullor omitted (generalised ufunc signatures are not supported).
Returns
VectorizedFn
Example
const vf = np.vectorize((x, y) => x + y);
vf([1, 2], [10, 20]).toArray(); // => [11, 22]
vf.pyfunc(3, 4); // => 7TypeScript declaration
np.vectorize(fn: (...args: unknown[]) => unknown, opts?: VectorizeOptions | undefined): VectorizedFnnp.shares_memory
#np.shares_memory(a, b, [options])
Returns true if arrays a and b share any underlying memory. Delegates to native buffer identity and byte-range overlap. maxWork is accepted for NumPy API compatibility but ignored.
Parameters
aNDArray- First array.
bNDArray- Second array.
[options.maxWork]number- Accepted but not used.
Returns
boolean
Example
const a = np.array([1, 2, 3]);
const b = a.slice([[0, 2]]);
np.shares_memory(a, b); // => true
np.shares_memory(a, np.array([1, 2, 3])); // => falsenp.cumsum
#np.cumsum(a, [axis], [options])
Cumulative sum of array elements along the given axis. If axis is omitted or null, the array is flattened first.
Parameters
aArrayLike- Input array.
[axis]number | null- Axis to accumulate along;
nullflattens first. [options.dtype]DTypeLike- Accumulator dtype.
Returns
NDArray
Example
np.cumsum([1, 2, 3]).toArray(); // => [1, 3, 6]
np.cumsum([[1, 2], [3, 4]], 0).toArray(); // => [[1, 2], [4, 6]]TypeScript declaration
np.cumsum(a: NDArray | NestedArray, axis?: number | null | undefined, opts?: { dtype?: DTypeLike | null | undefined; } | undefined): NDArraynp.cumprod
#np.cumprod(a, [axis], [options])
Cumulative product of array elements along the given axis. If axis is omitted or null, the array is flattened first.
Parameters
aArrayLike- Input array.
[axis]number | null- Axis to accumulate along;
nullflattens first. [options.dtype]DTypeLike- Accumulator dtype.
Returns
NDArray
Example
np.cumprod([1, 2, 3, 4]).toArray(); // => [1, 2, 6, 24]
np.cumprod([[1, 2], [3, 4]], 1).toArray(); // => [[1, 2], [3, 12]]TypeScript declaration
np.cumprod(a: NDArray | NestedArray, axis?: number | null | undefined, opts?: { dtype?: DTypeLike | null | undefined; } | undefined): NDArraynp.nancumsum
#np.nancumsum(a, opts?) · np.nancumprod(a, opts?)
Like cumsum/cumprod but NaN values are treated as 0 / 1 respectively (i.e. they are skipped).
Parameters
aArrayLike- Input array.
[opts.axis]number | null- Axis; default flattened.
[opts.dtype]DTypeLike- Accumulator dtype.
Returns
NDArray
Example
np.nancumsum([1, NaN, 2]).toArray(); // => [1, 1, 3]
np.nancumprod([2, NaN, 3]).toArray(); // => [2, 2, 6]TypeScript declaration
np.nancumsum(a: ArrayLike, opts?: CumsumOptions | undefined): NDArray
np.nancumprod(a: ArrayLike, opts?: CumsumOptions | undefined): NDArraynp.busdaycalendar
#new np.busdaycalendar([options])
A business-day calendar combining a weekmask (which weekdays are business days) and optional holidays. Used with is_busday, busday_count, and busday_offset.
Parameters
[options.weekmask]string | boolean[]- 7-character bit string
"1111100", a space-separated list of day names like"Mon Tue Wed Thu Fri", or a boolean array. Defaults to Mon–Fri. [options.holidays](string | number | bigint)[]- List of holiday dates as ISO-8601 strings or epoch-day integers.
Returns
busdaycalendar
Example
new np.busdaycalendar({ weekmask: "Mon Tue Wed Thu Fri" }).weekmask[0]; // => truenp.is_busday
#np.is_busday(dates, [options])
Return true for each date that is a business day (not a weekend and not a holiday).
Parameters
datesstring | number | DatetimeArray | Array- One or more dates.
[options.weekmask]string | boolean[]- Which weekdays count as business days. Defaults to Mon–Fri.
[options.holidays](string | number | bigint)[]- Holidays to exclude.
[options.busdaycal]busdaycalendar- Pre-built calendar; overrides weekmask/holidays.
Returns
boolean | boolean[]
Example
np.is_busday("2023-01-16"); // => trueTypeScript declaration
np.is_busday(dates: string | number | bigint | DatetimeArray | (string | number | bigint | DatetimeArray)[], options?: IsBusdayOptions | undefined): boolean | boolean[]np.busday_count
#np.busday_count(begindates, enddates, [options])
Count the number of business days in [begindates, enddates). Negative when end < begin.
Parameters
begindatesstring | number | DatetimeArray- Start date(s), inclusive.
enddatesstring | number | DatetimeArray- End date(s), exclusive.
[options.weekmask]string | boolean[]- Which weekdays count. Defaults to Mon–Fri.
[options.holidays](string | number | bigint)[]- Holidays to exclude.
[options.busdaycal]busdaycalendar- Pre-built calendar.
Returns
number | number[]
Example
np.busday_count("2023-01-01", "2023-01-08"); // => 5TypeScript declaration
np.busday_count(begindates: string | number | bigint | DatetimeArray, enddates: string | number | bigint | DatetimeArray, options?: BusdayCountOptions | undefined): number | number[]np.busday_offset
#np.busday_offset(dates, offsets, [options])
Shift dates by offsets business days. The roll option controls what to do when a date falls on a non-business day before stepping.
Parameters
datesstring | number | DatetimeArray | Array- Starting date(s).
offsetsnumber | number[]- Number of business days to advance (positive) or retreat (negative).
[options.roll]string"raise"(default),"nat","forward","following","backward","preceding","modifiedfollowing","modifiedpreceding".[options.weekmask]string | boolean[]- Which weekdays count. Defaults to Mon–Fri.
[options.holidays](string | number | bigint)[]- Holidays to exclude.
[options.busdaycal]busdaycalendar- Pre-built calendar.
Returns
DatetimeArray | DatetimeArray[]
Example
np.busday_offset("2023-01-16", 5).toString(); // => "2023-01-23"TypeScript declaration
np.busday_offset(dates: string | number | bigint | DatetimeArray | (string | number | bigint | DatetimeArray)[], offsets: number | number[], options?: BusdayOffsetOptions | undefined): DatetimeArray | DatetimeArray[] | nullnp.sharesMemory
#np.sharesMemory(a, b, [options])
Return true if a and b share the same underlying memory buffer (NumPy np.shares_memory). Unlike mayShareMemory, this is always an exact check.
Parameters
aNDArray- First array.
bNDArray- Second array.
[options.maxWork]number- Ignored (always exact).
Returns
boolean
Example
const a = np.arange(6);
const b = a.reshape([2, 3]);
np.sharesMemory(a, b); // => true
np.sharesMemory(a, np.array([1, 2])); // => falseTypeScript declaration
np.sharesMemory(a: NDArray, b: NDArray, _opts?: SharesMemoryOptions | undefined): boolean