Chapter 7: Miscellaneous

Loading and saving arrays

face Josiah Wang

You can save and load NumPy arrays onto/from the disk.

Save as a binary file

The first option is to save them as binary files. These are actually Python pickle files.

Use np.save() and np.load() to save/load ONE np.array to/from disk. Note there is no need to provide the extension *.npy when saving!

>>> x = np.array([1, 2, 3, 4, 5, 6])
>>> np.save("myfile", x)
>>> x_fromdisk = np.load("myfile.npy")
>>> print(x_fromdisk)
[1 2 3 4 5 6]

Use np.savez() to save multiple arrays as a single *.npz file (it is a zip file). Again, no need to provide the *.npz extension when saving!

>>> x = np.array([1, 2, 3, 4, 5, 6])
>>> y = np.array([[1, 2], [3, 4]])
>>> np.savez("multiple", x=x, y=y)
>>> arr_fromdisk = np.load("multiple.npz")
>>> print(arr_fromdisk["x"])
[1 2 3 4 5 6]
>>> print(arr_fromdisk["y"])
[[1 2]
 [3 4]]

Save as a text file

The second option is to save them as text files. Use np.savetxt() and np.loadtxt().

>>> x = np.array([1, 2, 3, 4, 5, 6])
>>> np.savetxt("myfile.csv", x)
>>> x_fromtext = np.loadtxt("myfile.csv")
>>> print(x_fromtext)
[1. 2. 3. 4. 5. 6.]