Saving and Loading NumPy Data
Why save NumPy arrays?
Section titled “Why save NumPy arrays?”Saving arrays lets you:
- reuse cleaned/processed features
- speed up workflows (avoid re-parsing CSV)
- share data between scripts/notebooks
NumPy’s own binary format is .npy (one array) / .npz (multiple arrays) — uncompressed by default, and much faster to reload than re-parsing text.
Save and load single array: .npy
Section titled “Save and load single array: .npy”import numpy as np
arr = np.arange(10)
np.save("my_array.npy", arr)import numpy as np
arr2 = np.load("my_array.npy")
print(arr2) flowchart TD
A["Need to persist array data"] --> B{"One array or several?"}
B -- "One" --> C["np.save('file.npy', arr)"]
B -- "Several" --> D["np.savez('file.npz', a=arr1, b=arr2)"]
A --> E{"Need it human-readable
or shared as plain text?"}
E -- "Yes" --> F["np.savetxt / np.loadtxt"]
D --> G{"Compresses well?"}
G -- "Yes" --> H["np.savez_compressed"]
Save and load multiple arrays: .npz
Section titled “Save and load multiple arrays: .npz”If the file path doesn’t end in .npy/.npz, NumPy appends the extension automatically.
import numpy as np
x = np.arange(5)
y = np.arange(5) ** 2
np.savez("data.npz", x=x, y=y)
loaded = np.load("data.npz")
print(loaded.files)
print(loaded["x"], loaded["y"])If the saved data compresses well, np.savez_compressed produces a smaller file at the cost of a bit more CPU time:
import numpy as np
arr = np.arange(10)
np.savez_compressed("arrays_compressed.npz", a=arr, b=arr)Text formats (CSV-like)
Section titled “Text formats (CSV-like)”Save to text
Section titled “Save to text”import numpy as np
mat = np.array([[1.1, 2.2], [3.3, 4.4]])
np.savetxt("matrix.csv", mat, delimiter=",", fmt="%.2f")Load from text
Section titled “Load from text”import numpy as np
mat2 = np.loadtxt("matrix.csv", delimiter=",")
print(mat2)- For best speed and exact dtype preservation: use
.npy/.npz. - Use
.npzwhen you want one file containing multiple arrays.
Continue to: Conditional Logic, Sorting & Set Logic to express if-style logic as array operations and use sort, unique, and set functions.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Save a Single Array
Section titled “Exercise 1 – Save a Single Array”Exercise 2 – Save Multiple Arrays with savez
Section titled “Exercise 2 – Save Multiple Arrays with savez”Exercise 3 – Round-trip Through a Text File
Section titled “Exercise 3 – Round-trip Through a Text File”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading