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:
np.save('scores.npy', a) # one arrayback = np.load('scores.npy') # exact round-trip (dtype & shape kept)np.savez('data.npz', x=a, y=b) # multiple arraysd = np.load('data.npz')d['x'], d['y'] # access by the names you gavenp.savez_compressed('data.npz', x=a) # compressed variant
Text & CSV
# 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
a.tolist() # ndarray → nested Python listnp.asarray([[1, 2], [3, 4]]) # list → array (no copy if already one)import pandas as pddf = pd.DataFrame(a) # array → DataFramearr = 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:
big = np.load('huge.npy', mmap_mode='r') # doesn't load it allchunk = 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
- 01np.save/np.load use the .npy binary format — fast, lossless, dtype- and shape-preserving.
- 02np.savez bundles several arrays into one .npz (savez_compressed to shrink it).
- 03loadtxt reads clean numeric text; genfromtxt tolerates missing values.
- 04Convert freely: tolist, np.asarray, and to/from pandas via DataFrame(a) / df.to_numpy().
- 05np.memmap / mmap_mode reads arrays larger than RAM in slices from disk.
