typestar

Saving arrays in Python

npy for one array, npz for several, savetxt when a human must read it.

import numpy as np

grid = np.arange(6).reshape(2, 3)
labels = np.array(["a", "b"])

np.save("grid.npy", grid)
np.savez("bundle.npz", grid=grid, labels=labels)
np.savetxt("grid.csv", grid, fmt="%d", delimiter=",")

print(np.load("grid.npy"))
with np.load("bundle.npz") as bundle:
    print(sorted(bundle.files), bundle["labels"])
print(np.loadtxt("grid.csv", delimiter=",", dtype=int))

How it works

  1. save writes a single array with its dtype and shape.
  2. savez bundles named arrays into one archive.
  3. loadtxt and savetxt trade speed for legibility.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
381
Tokens
143
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 78 seconds.

Type this snippet

Step 2 of 2 in Randomness & storage, step 21 of 22 in NumPy.

← Previous Next →