Skip to main content
Albero Academy

Saving, Loading & Interoperability

Persist arrays to disk with the .npy/.npz formats, read text and CSV data, and move arrays to and from pandas and lists.

Chapter 15NumPy13 min readBeginner friendly
  • #NumPy
  • #File I/O
  • #Interop

Arrays need to leave memory — saved between runs, shared with colleagues, loaded from a data file. NumPy has a fast native binary format for its own arrays and readers for text data, and it converts cleanly to and from the rest of the Python ecosystem.

The .npy & .npz formats

np.save writes one array to a .npy file — fast, exact and preserving dtype and shape. np.savez bundles several into one .npz:

native binary I/O
np.save('scores.npy', a) # one array
back = np.load('scores.npy') # exact round-trip (dtype & shape kept)
np.savez('data.npz', x=a, y=b) # multiple arrays
d = np.load('data.npz')
d['x'], d['y'] # access by the names you gave
np.savez_compressed('data.npz', x=a) # compressed variant

Text & CSV

reading & writing text
# Read numeric CSV (skip a header row)
data = np.loadtxt('marks.csv', delimiter=',', skiprows=1)
# genfromtxt tolerates missing values (fills them with nan)
data = np.genfromtxt('marks.csv', delimiter=',', names=True)
np.savetxt('out.csv', a, delimiter=',', fmt='%.2f') # write CSV

Lists, pandas & beyond

convert in and out
a.tolist() # ndarray → nested Python list
np.asarray([[1, 2], [3, 4]]) # list → array (no copy if already one)
import pandas as pd
df = pd.DataFrame(a) # array → DataFrame
arr = df.to_numpy() # DataFrame → array (the bridge to the next course)

Memory-mapping big files

For arrays too large to fit in RAM, np.memmap (or mmap_mode in load) maps the file on disk so you read pieces on demand:

data bigger than memory
big = np.load('huge.npy', mmap_mode='r') # doesn't load it all
chunk = big[1000:2000] # only this slice is read

Practice

Save an array to .npy, reload it, and confirm it's identical (np.array_equal). Bundle two arrays into an .npz and read them back by name. Read a small CSV with np.loadtxt, then convert an array to a pandas DataFrame and back.

Key takeaways

  1. 01np.save/np.load use the .npy binary format — fast, lossless, dtype- and shape-preserving.
  2. 02np.savez bundles several arrays into one .npz (savez_compressed to shrink it).
  3. 03loadtxt reads clean numeric text; genfromtxt tolerates missing values.
  4. 04Convert freely: tolist, np.asarray, and to/from pandas via DataFrame(a) / df.to_numpy().
  5. 05np.memmap / mmap_mode reads arrays larger than RAM in slices from disk.