Skip to content

Saving and Loading NumPy Data

Why save NumPy arrays?

Saving arrays lets you:

  • reuse cleaned/processed features
  • speed up workflows (avoid re-parsing CSV)
  • share data between scripts/notebooks

Save and load single array: .npy.npy

Save

save
import numpy as np
 
arr = np.arange(10)
np.save("my_array.npy", arr)
save
import numpy as np
 
arr = np.arange(10)
np.save("my_array.npy", arr)

Load

load
import numpy as np
 
arr2 = np.load("my_array.npy")
print(arr2)
load
import numpy as np
 
arr2 = np.load("my_array.npy")
print(arr2)

Save and load multiple arrays: .npz.npz

npz
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"])
npz
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"])

Text formats (CSV-like)

Save to text

savetxt
import numpy as np
 
mat = np.array([[1.1, 2.2], [3.3, 4.4]])
np.savetxt("matrix.csv", mat, delimiter=",", fmt="%.2f")
savetxt
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

loadtxt
import numpy as np
 
mat2 = np.loadtxt("matrix.csv", delimiter=",")
print(mat2)
loadtxt
import numpy as np
 
mat2 = np.loadtxt("matrix.csv", delimiter=",")
print(mat2)

Tips

  • For best speed and exact dtype preservation: use .npy.npy / .npz.npz.
  • Use .npz.npz when you want one file containing multiple arrays.

Next

Phase 2 is complete. Next is Phase 3: Data Manipulation (Pandas) with Introduction to Pandas.

๐Ÿงช Try It Yourself

Exercise 1 โ€“ Create a NumPy Array

Exercise 2 โ€“ Array Shape and Reshape

Exercise 3 โ€“ Array Arithmetic

If this helped you, consider buying me a coffee โ˜•

Buy me a coffee

Was this page helpful?

Let us know how we did