NumPy Saving/Loading with .npy Files
NumPy provides built-in support for saving and loading arrays efficiently using the .npy binary format. This format is ideal for storing large numerical data with full fidelity, preserving data types and shapes.
Key Features of NumPy's I/O with .npy:
- Fast storage and loading: Binary format is optimized for NumPy arrays.
- Preserves structure: Retains array shape, dtype, and metadata.
- Single-array focus: Designed to store one array per file (for multiple arrays, use np.savez()).
- Compatible: Easily shared and reused across Python environments with NumPy.
Learning how to persist and reload arrays using np.save() and np.load() is essential for efficient data workflows, caching computations, or storing intermediate results in scientific computing.
Saving NumPy Arrays with np.save()
The np.save() function saves a NumPy array to a file in .npy format — a binary format that's efficient and preserves all array metadata (shape, dtype, etc.). This is ideal for caching intermediate results or storing data for later use.
Basic Usage
import numpy as np
arr = np.array([[10, 20, 30],
[40, 50, 60]])
# Save array to 'data.npy' in current directory
np.save('data.npy', arr)
print("Array saved to 'data.npy'")
import numpy as np
arr = np.array([[10, 20, 30],
[40, 50, 60]])
# Save array to 'data.npy' in current directory
np.save('data.npy', arr)
print("Array saved to 'data.npy'")
What This Does
- 'data.npy' is the filename where the array is saved.
- The file is saved in binary format (not human-readable).
- No file extension is automatically added if one is present, but .npy is appended if omitted.
Output
Array saved to 'data.npy'
Array saved to 'data.npy'
💡 Tip: If you're saving arrays to a specific path, make sure the folder exists or handle it with os.makedirs().
Loading NumPy Arrays with np.load()
To read a NumPy array back into memory, use the np.load() function. This works with any array saved using np.save() and reconstructs the original array, including its shape and data type.
Basic Usage
import numpy as np
# Load array from file
loaded_arr = np.load('data.npy')
print("Loaded array:")
print(loaded_arr)
import numpy as np
# Load array from file
loaded_arr = np.load('data.npy')
print("Loaded array:")
print(loaded_arr)
How It Works
- Reconstructs the array from the binary .npy file.
- Works even for multi-dimensional or complex-typed arrays.
- Returns a fully functional ndarray object.
Output
Loaded array:
[[10 20 30]
[40 50 60]]
Loaded array:
[[10 20 30]
[40 50 60]]
💡 Tip: Make sure the file path is correct. If the file doesn't exist or is corrupted, np.load() will raise an error.
Frequently Asked Questions
How do I save a NumPy array to a .npy file?
How do I save a NumPy array to a .npy file?
You can save a NumPy array to a `.npy` file using the np.save() function. For example: np.save('filename.npy', arr).
How can I load a NumPy array from a .npy file?
How can I load a NumPy array from a .npy file?
To load a NumPy array from a `.npy` file, use np.load(). Example: arr = np.load('filename.npy').
What is the .npy file format?
What is the .npy file format?
The .npy format is a binary format used by NumPy to store arrays, preserving important information like shape, dtype, and metadata.
Can I save multiple arrays in one .npy file?
Can I save multiple arrays in one .npy file?
No, a single `.npy` file can only store one array. For saving multiple arrays, you should use np.savez(), which creates a compressed archive of arrays.
How do I handle errors while loading a .npy file?
How do I handle errors while loading a .npy file?
If an error occurs when loading a `.npy` file (e.g., file not found or corrupted), an OSError will be raised. Handle it using a try-except block.
Can I load arrays with different shapes from the same .npy file?
Can I load arrays with different shapes from the same .npy file?
You cannot store multiple arrays with different shapes in a single `.npy` file, but you can use np.savez() to save multiple arrays in a single compressed file (.npz).
What's Next?
Now that you've completed the core concepts of NumPy, it’s time to practice NumPy to perfect yourself.