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
savewrites a single array with its dtype and shape.savezbundles named arrays into one archive.loadtxtandsavetxttrade speed for legibility.
Keywords and builtins used here
asintprintsortedwith
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.
Step 2 of 2 in Randomness & storage, step 21 of 22 in NumPy.