NumPy
Saving and Loading
Persist arrays with .npy, .npz, and text formats.
By EZ4Code Team
iopersistence
Code
import numpy as np
a = np.arange(10)
b = np.random.rand(3, 3)
# Single array
np.save("a.npy", a)
loaded = np.load("a.npy")
# Multiple arrays
np.savez("multi.npz", a=a, b=b)
data = np.load("multi.npz")
print(data["a"], data["b"])
# Compressed
np.savez_compressed("multi.npz", a=a, b=b)
# Text formats
np.savetxt("a.csv", b, delimiter=",", fmt="%.4f")
from_file = np.loadtxt("a.csv", delimiter=",")Explanation
save and load handle single arrays in the binary .npy format, while savez bundles several arrays into a .npz archive that loads like a dict. savez_compressed shrinks storage at the cost of CPU. savetxt and loadtxt exchange data in human-readable CSV or whitespace formats.
More NumPy Snippets
Array Creation
Create arrays from lists and built-in constructors.
Indexing and Slicing
Slice arrays and index with boolean masks.
Broadcasting
Combine arrays of compatible shapes without copying.
Math Operations
Apply element-wise math and reductions.
Linear Algebra
Solve systems, factorize, and compute eigenvalues.
Random Numbers
Sample from distributions with a Generator.