API reference
Input and output
NumPy .npy/.npz files and text files. Paths are read and written with Node's fs. Pass null instead of a path to get the bytes back as a Buffer, and pass bytes to load instead of a path.
| Name | Summary |
|---|---|
np.save | Writes one array in NumPy's .npy format, byte for byte as NumPy writes it. |
np.load | Reads a .npy file (returns an NDArray) or a .npz archive (returns an NpzFile). |
np.savez | Writes several arrays to an uncompressed .npz zip archive. |
np.savezCompressed | Like savez, but the members are deflate-compressed (with Node's zlib). |
np.NpzFile | A loaded .npz archive. |
np.loadtxt | Reads a numeric table from a text file. |
np.savetxt | Writes a 1-D or 2-D array as text with Python %-formatting (d i u o x X e E f F g G s). |
np.genfromtxt | Reads a table and fills missing or invalid cells. |
np.fromregex | Every match of regexp in the text is a record, and its capture groups fill the fields of dtype. |
np.fromfile | Reads raw binary data, as written by a.tofile(), or a text file of numbers separated by sep. |
np.tofile | Method of NDArray. |
np.save
#np.save(file, arr)
Writes one array in NumPy's .npy format, byte for byte as NumPy writes it. Supported dtypes: bool, integers, floats and complex.
Parameters
filestring | URL | null- Path to write (the extension is appended when missing), or
nullto return the bytes as aBuffer. arrArrayLike- Array to save.
Returns
Buffer when `file` is null, otherwise undefined
Example
np.save(null, [1, 2, 3]).length; // => 152
np.save(null, [1, 2, 3]).subarray(1, 6).toString(); // => "NUMPY"TypeScript declaration
np.save(file: FileLike, arr: ArrayLike): anynp.load
#np.load(file, [options])
Reads a .npy file (returns an NDArray) or a .npz archive (returns an NpzFile). Reads big-endian data and Fortran-ordered arrays. Pickled object arrays and mmapMode are not supported.
Parameters
filestring | URL | Buffer | Uint8Array | ArrayBuffer- Path, or the file contents.
[options.mmapMode]null- Only
null(no memory mapping).
Returns
NDArray | NpzFile
Example
np.load(np.save(null, [[1, 2], [3, 4]])); // => [[1, 2], [3, 4]]
np.load(np.save(null, np.ones(2, { dtype: "float32" }))).dtype.name; // => "float32"TypeScript declaration
np.load(file: string | URL | BytesLike, options?: LoadOptions | undefined): NDArray | NpzFilenp.savez
#np.savez(file, ...arrays, [named])
Writes several arrays to an uncompressed .npz zip archive. Positional arrays are named arr_0, arr_1, ...; a trailing plain object maps names to arrays (NumPy keyword arguments). The output is byte-identical to NumPy's.
Parameters
filestring | URL | null- Path to write (the extension is appended when missing), or
nullto return the bytes as aBuffer. arraysArrayLike[]- Arrays to store.
[named]Record<string, ArrayLike>- Arrays stored under their keys.
Returns
Buffer when `file` is null, otherwise undefined
Example
np.load(np.savez(null, [1, 2], { w: [3] })).files; // => ["w", "arr_0"]TypeScript declaration
np.savez(file: FileLike, ...arrays: (ArrayLike | NamedArrays)[]): anynp.savezCompressed
#np.savezCompressed(file, ...arrays, [named])
Like savez, but the members are deflate-compressed (with Node's zlib).
Parameters
filestring | URL | null- Path to write (the extension is appended when missing), or
nullto return the bytes as aBuffer. arraysArrayLike[]- Arrays to store.
[named]Record<string, ArrayLike>- Arrays stored under their keys.
Returns
Buffer when `file` is null, otherwise undefined
Example
np.load(np.savezCompressed(null, { x: np.zeros(3) })).get("x"); // => [0, 0, 0]TypeScript declaration
np.savezCompressed(file: FileLike, ...arrays: (ArrayLike | NamedArrays)[]): anynp.NpzFile
#np.load(npz) → NpzFile
A loaded .npz archive. files lists the member names without .npy; get(name) decodes one member (NumPy npz[name]); also has, keys, entries, iteration over names and close().
Returns
NpzFile
Example
const z = np.load(np.savez(null, { a: [1, 2], b: [true] }));
z instanceof np.NpzFile; // => true
z.get("a.npy"); // => [1, 2]
[...z]; // => ["a", "b"]
z.has("c"); // => falseTypeScript declaration
np.load(file: string | URL | BytesLike, options?: LoadOptions | undefined): NDArray | NpzFilenp.loadtxt
#np.loadtxt(fname, [options])
Reads a numeric table from a text file. Blank lines and comments are skipped and every row must have the same number of columns. The result is squeezed (one row or one column gives a 1-D array), then ndmin and unpack are applied. Only numeric and bool dtypes are supported (bool cells are integers).
Parameters
fnamestring | URL | Uint8Array | string[]- Path (
.gzis decompressed), the contents as bytes, or a list of lines. [options.dtype]DTypeLike- Default
float64. [options.delimiter]string | null- One character;
null(default) splits on whitespace. [options.comments]string | string[] | null- Comment prefixes (default
"#"). [options.skiprows]number- Leading lines to skip.
[options.usecols]number | number[]- Columns to read; negative indices count from the end.
[options.maxRows]number- Read at most this many rows.
[options.unpack]boolean- Transpose the result.
[options.ndmin]0 | 1 | 2- Minimum number of dimensions.
[options.quotechar]string- Quote character for fields that contain the delimiter.
Returns
NDArray
Example
np.loadtxt(["# x y", "1 2", "3 4"]); // => [[1, 2], [3, 4]]
np.loadtxt(Buffer.from("1,2\n3,4\n"), { delimiter: ",", usecols: 1, dtype: "int32" }); // => [2, 4]
np.loadtxt(["1 2 3"], { ndmin: 2 }).shape; // => [1, 3]TypeScript declaration
np.loadtxt(fname: TextSource, options?: LoadtxtOptions | undefined): NDArraynp.savetxt
#np.savetxt(fname, X, [options])
Writes a 1-D or 2-D array as text with Python %-formatting (d i u o x X e E f F g G s). A 1-D array is written as one column. With one format, complex values are written as (re+imj). A path ending in .gz is gzip-compressed.
Parameters
fnamestring | URL | null- Path to write, or
nullto return the text. XArrayLike- 1-D or 2-D data.
[options.fmt]string | string[]- One format, one per column, or a whole-row format. Default
"%.18e". [options.delimiter]string- Column separator (default
" "). [options.newline]string- Line terminator (default
"\n"). [options.header]string- Text written before the data, each line prefixed by
comments. [options.footer]string- Text written after the data.
[options.comments]string- Prefix for header and footer lines (default
"# ").
Returns
string when `fname` is null, otherwise undefined
Example
np.savetxt(null, [[1, 2], [3, 4]], { fmt: "%d", delimiter: "," }); // => "1,2\n3,4\n"
np.savetxt(null, [0.5, 1e16], { fmt: "%s", header: "v" }); // => "# v\n0.5\n1e+16\n"TypeScript declaration
np.savetxt(fname: string | URL | null, X: ArrayLike, options?: SavetxtOptions | undefined): string | undefinednp.genfromtxt
#np.genfromtxt(fname, [options])
Reads a table and fills missing or invalid cells. Cells that do not convert become filling values: NaN for floats, -1 for integers, false for bool, unless loose is false (then only missingValues are filled). Bool cells are true/false in any case. A numeric dtype is required (no type inference, names, converters or masks).
Parameters
fnamestring | URL | Uint8Array | string[]- Path, contents as bytes, or a list of lines.
[options.dtype]DTypeLike- Default
float64. [options.delimiter]string | number | number[]- Separator, a field width, or field widths. Default: whitespace.
[options.comments]string | null- Comment marker (default
"#"). [options.skipHeader]number- Lines to skip at the start.
[options.skipFooter]number- Lines to drop at the end.
[options.missingValues]string | string[] | {col: value} | Map- Strings that mean missing (a string is split at
,). [options.fillingValues]value | value[] | {col: value} | Map- Replacement for missing or invalid cells.
[options.usecols]number | number[]- Columns to read.
[options.invalidRaise]boolean- Raise on rows with a wrong column count (default true), or drop them with a warning.
[options.loose]boolean- Fill unconvertible cells (default true).
[options.autostrip]boolean- Strip spaces around fields.
[options.maxRows]number- Read at most this many rows.
[options.unpack]boolean- Transpose the result.
[options.ndmin]0 | 1 | 2- Minimum number of dimensions.
Returns
NDArray
Example
np.isnan(np.genfromtxt(["1,2", "3,"], { delimiter: "," })); // => [[false, false], [false, true]]
np.genfromtxt(["1 x", "3 4"], { dtype: "int32", fillingValues: 0 }); // => [[1, 0], [3, 4]]
np.genfromtxt(["12345"], { delimiter: [2, 3], dtype: "int32" }); // => [12, 345]TypeScript declaration
np.genfromtxt(fname: TextSource, options?: GenfromtxtOptions | undefined): NDArraynp.fromregex
#np.fromregex(file, regexp, dtype)
Every match of regexp in the text is a record, and its capture groups fill the fields of dtype. Structured arrays are not available, so the result is an object with one 1-D array per field.
Parameters
filestring | URL | Uint8Array | string[]- Path, contents as bytes, or a list of lines.
regexpRegExp | string- Pattern; the
gflag is added. dtype[name, DTypeLike][]- Field names and dtypes, one per capture group.
Returns
Record<string, NDArray>
Example
const r = np.fromregex(["a=1 b=22"], /(\w)=(\d+)/, [["key", "bool"], ["n", "int32"]]);
r.n; // => [1, 22]TypeScript declaration
np.fromregex(file: TextSource, regexp: string | RegExp, dtype: FieldList): Record<string, NDArray>np.fromfile
#np.fromfile(file, [options])
Reads raw binary data, as written by a.tofile(), or a text file of numbers separated by sep. Binary data has no header, so you must give the dtype. A trailing partial item is ignored.
Parameters
filestring | URL | Uint8Array- Path, or the file contents.
[options.dtype]DTypeLike- Default
float64. [options.count]number- Items to read; -1 (default) reads all.
[options.sep]string- Item separator; empty (default) means binary.
[options.offset]number- Bytes to skip (binary mode only).
Returns
NDArray
Example
np.fromfile(np.array([1, 2, 3]).astype("int16").tofile(null), { dtype: "int16" }); // => [1, 2, 3]
np.fromfile(Buffer.from("1, 2, 3"), { sep: ",", count: 2 }); // => [1, 2]TypeScript declaration
np.fromfile(file: string | URL | Uint8Array<ArrayBufferLike>, options?: FromfileOptions | undefined): NDArraynp.tofile
#a.tofile(file, [options])
Method of NDArray. Writes the items in C order as raw bytes in native byte order, or with a sep as text where each item is formatted like Python str (or with format, a %-format). No shape or dtype is stored; use save to keep them.
Parameters
filestring | URL | null- Path to write, or
nullto return the bytes. [options.sep]string- Item separator; empty (default) writes binary.
[options.format]string- Format applied to each item in text mode, e.g.
"%.2f".
Returns
Buffer when `file` is null, otherwise undefined
Example
np.array([[1.5, 2], [3, 4]]).tofile(null, { sep: "," }).toString(); // => "1.5,2.0,3.0,4.0"
np.array([1, 2]).tofile(null, { sep: " ", format: "%03d" }).toString(); // => "001 002"
np.arange(3).astype("uint8").tofile(null).length; // => 3TypeScript declaration
a.tofile(file: string | URL | null, options?: TofileOptions | undefined): any